Reputation: 223
I came across a blog post arguing that the following is an antipattern:
def some_view(request):
form = MyForm(request.POST or None)
# …
Source: https://www.django-antipatterns.com/antipattern/using-request-post-or-none.html
However, I'm not clear on the problems that using it could cause. I have used this to keep my views concise, without noticing any unexpected behavior.
Is this an antipattern? If so, why?
The blog indicates that if the POST request has no content request.POST or None
will evaluate to None
, and so the form will be unbounded even though this was a POST. However, what I'm still unclear on is in what circumstance you could have a request.POST
that contains no content? Even if the form is submitted without inputs, the request.POST
contains a QueryDict, such as <QueryDict: {'csrfmiddlewaretoken': ['1XvPLekeY3sWxcaKzOAXODQBCUCYCz0W0QYhseDkEMUgdUfuiw4Exhq05fH0DxZ1'], 'email': [''], 'screen_name': [''], 'password1': [''], 'password2': ['']}>
. (Assuming the form has fields, how would the QueryDict be empty?)
I don't understand how the concern about a form being unbounded after an empty POST request could arise in a realistic scenario (or in any scenario, to be honest). How can a user submit a form causing the view to receive a contentless POST request?
Upvotes: 1
Views: 243
Reputation: 45806
The site explains why this is problematic:
This means that even if it is a POST request, it will take None, and thus as result the form is not bounded.
You can see that if you poke through the source. The first argument to the form initializer is data
, and the initializer contains this line:
self.is_bound = data is not None or files is not None
As mentioned, if data
is None
, the form will not be considered to be bound. This has the consequence of the form never being considered to be valid:
def is_valid(self):
"""Return True if the form has no errors, or False otherwise."""
return self.is_bound and not self.errors
This would be problematic if you're doing proper validation on the form after.
Upvotes: 1