Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 516
Art Avatar asked May 30 '10 04:05

Art


People also ask

How do I see requests in Django?

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).

What is request method == POST in Django?

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).

How does Django define request?

Django uses request and response objects to pass state through the system. When a page is requested, Django creates an HttpRequest object that contains metadata about the request. Then Django loads the appropriate view, passing the HttpRequest as the first argument to the view function.

What is the purpose of __ Str__ method in Django?

str function in a django model returns a string that is exactly rendered as the display name of instances for that model.


1 Answers

The documentation is clear about this:

  • http://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.POST

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
like image 68
miku Avatar answered Sep 20 '22 07:09

miku