django request.POST vs request.method
Properly processing requests in your views is important, and one of the most important things is knowing what HTTP verb is being used.
There are few ways to determine whether you are getting a GET
or POST
. The two most common ways people determine this is:
if request.POST:
pass
or
if request.method == 'POST':
pass
It is important to know the difference between the two. While they do get you to the same place there are a couple of caveats to note.
request.method
This actually returns a string of the method used with the request, and nothing else. This is important because you can use HTTP verbs without sending data.
request.POST
If you do a boolean check of request.POST it checks to make sure that there is data in the POST
QueryDict
dictionary like object. If there is data then it was a POST
; if no data then it evaluates as false as if no POST
happened.
The problem is you can do a POST
even without data and if you do you would get the following result: (captured from the shell)
request.POST
<QueryDict: {}>
Which means there is no data so your code says “this is not a POST
” when it really is one.
Conclusion
If you don’t know how these two different parts of the framework work then it can lead to a lot of headache when you get results you don’t expect. I recommend to always use request.method
instead of evaluating if the QueryDict
has data in it from a GET
or a POST
. It can lead to headaches in logic in some few instances, and is more explicit as to what is being evaluated.