Tuesday, April 5, 2011

Check request type in Django

While it is recommended to use the following construct to check whether request is POST,

if request.method == 'POST':
    pass

It is likely that people will find

if request.POST:
    pass

to be more elegant and concise.

Are there any reasons not to use it, apart from personal preference?

From stackoverflow
  • The documentation is clear about this:

    It's possible that a request can come in via POST with an empty POST dictionary -- if, say, a form is requested via the POST HTTP method but does not include form data. Therefore, you shouldn't use if request.POST to check for use of the POST method; instead, use if request.method == "POST" (see above).

    >>> # assume an empty POST request would be treated as a dict
    >>> bool({})
    False
    >>> # it would be a POST request, but request.POST would evaluate to False
    

0 comments:

Post a Comment