pkaramol
pkaramol

Reputation: 19312

Handling POST data in django forms

What is the difference (if any) between the following 2 approaches when handling POST data in a form view:

1.

def form_view(request):
    form = MyForm(request.POST or None)
    if form.is_valid():
        # handle POST data here

2.

 def form_view(request):
     if request.method == "POST":
         form = MyForm(request.POST)
         if form.is_valid():
             # handle POST data here
     else:
         form = MyForm()

Upvotes: 2

Views: 612

Answers (2)

Alasdair
Alasdair

Reputation: 308779

Using request.POST or None is a shortcut, which is used to make the view shorter (although it makes it harder to understand if you haven't seen the technique before). It's useful to be familiar with this trick, because you'll come across it in other people's code. Most of the time, views will work the same whichever approach you take. However, there there are some edge cases, so the safest approach would be to avoid the trick.

The trick works because request.POST is an empty dict for GET requests. That means that:

  • request.POST or None is equivalent to {} or None for get requests, which evaluates to None.
  • request.POST or None evaluates to request.POST for post requests, as long as the post request is not empty.

Therefore, you can use MyForm(request.POST or None), instead of having to include the if statement and instantiate the form in both branches.

The edge cases occur for post requests when request.POST is empty. This is unusual, but can occur, for example if a form contains only checkboxes, and you submit it with none selected.

Upvotes: 4

Andrii Rusanov
Andrii Rusanov

Reputation: 4606

request.POST or None - will pass data to the form if request.POST is not empty(so it is POST request) otherwise it will pass None(and for will act in the same way with MyForm()).

If nothing has been passed to from it won't be valid, but not errors will be occured at the same time.

If something will be passed to form but data will be invalid, is_valid() will return False as well, but under form.errors raised errors will be placed.

Long story short, this way allows you to write code in more short and elegant manner.

Upvotes: 0

Related Questions