[Django]-What exactly does django request.POST do and how to use it?

1👍

There are some mistakes in the code and it seems it’s copy-pasted from a SO question. I would recommend going through the excellent Django documentation, especially the Django tutorial.

Your example should rather look like this example from the Django docs.

Here are some comments:

def create(request):
    if request.POST:
        form = ArticleForm(request.POST)
        if form.is_valid:
            form.save()
            # after successful POST
            # we want to redirect to a different page here
   else:
       form = ArticleForm()
   args = {}
   # you really don't need the following necessarily
   # just use `{% csrf_token %}` inside the form in your template
   args.update(csrf(request))
   args['form'] = form
   # using just `render` like in the example linked to above is more modern
   return render_to_response('create_article.html', args)

3👍

request.POST among other things (like the CSRF token value) contains all the data the user has entered in the form.

if request.POST

checks if the user actually validated the form, otherwise there is no POST data in the request.

form = ArticleForm(request.POST)

looks strange at first but when the user validates the form, the same page is loaded but the POST data is processed in the django form for data validation (like checking if a required field was left blank, etc…) in order to display errors in the form.
If there is no error (form.is_valid()) then the view program continues.

2👍

I hope you are familiar with HTTP methods like GET and POST.

request object represents a single request by any user agent. So it can be a request that’s sent from browser from you when you browse a particular page or from a crawler from a search engine. Read more about request here

request.POST is an attribute of this request object, it’s a QueryDict (much similar to a normal Python dict). It contains the HTTP POST parameters that are sent to your view.

In short in your example:

def create(request):
    if request.POST:  # check if the request is POST request and it contains any parameter  
        form = ArticleForm(request.POST)  # then pass all those parameters to the form
        if form.is_valid:  # process the form to check if it's valid
            form.save()  # save the data if it's valid
        else:
            form = ArticleForm()  # if not valid data, initialize an new / empty form
    args = {}  # create a dict to pass to the template
    args.update(csrf(request))  # add the CSRF token
    args['form'] = form  # add the 'form' above to the 'args' dict
    return render_to_response('create_article.html', args)  # pass that dict to template

Not so sure why you have this example, normally I would do the last part like this:

def create(request):
    .... your code ....
    else:
        form = ArticleForm()
    return render(request, 'create_article.html', { form: form })

Hope it helps.

Leave a comment