What does request.method == "POST" mean in Django?

user2657599 picture user2657599 · Oct 2, 2013 · Viewed 56.6k times · Source

I am using this thing in my views quite a lot but I want to know what exactly does that mean.

What happens when we write request.method == "GET" or request.method == "POST"?

Answer

Ludwik Trammer picture Ludwik Trammer · Oct 2, 2013

The result of request.method == "POST" is a boolean value - True if the current request from a user was performed using the HTTP "POST" method, of False otherwise (usually that means HTTP "GET", but there are also other methods).

You can read more about difference between GET and POST in answers to the question Alasadir pointed you to. In a nutshell POST requests are usually used for form submissions - they are required if processing a form would change server-side state (for example add user to a database, in case of a registration form). GET is used for normal HTTP requests (for example when you just type an URL into your browser) and for forms that can be processed without any side-effects (for example a search form).

The code is usually used in conditional statements, to distinguish between code for processing a submitted form, and code for displaying an unbound form:

if request.method == "POST":
    # HTTP Method POST. That means the form was submitted by a user
    # and we can find her filled out answers using the request.POST QueryDict
else:
    # Normal GET Request (most likely).
    # We should probably display the form, so it can be filled
    # out by the user and submitted. 

And here is another example, taken straight from Django documentation, using Django Forms library:

from django.shortcuts import render
from django.http import HttpResponseRedirect

def contact(request):
    if request.method == 'POST': # If the form has been submitted...
        form = ContactForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
            # ...
            return HttpResponseRedirect('/thanks/') # Redirect after POST
    else:
        form = ContactForm() # An unbound form

    return render(request, 'contact.html', {
        'form': form,
    })