o8tida
Last Updated: February 25, 2016
·
7.086K
· scott_woodall

Better Way To Initialize Django Forms

A common way for initializing forms is:

def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            # Process the data in form.cleaned_data
            return HttpResponseRedirect('/thanks/')
    else:
        form = ContactForm()

    return render(request, 'contact.html', {
        'form': form,
    })

A better way that DRYs things up and removes a conditional:

def contact(request):
    form = ContactForm(request.POST or None)
    if request.method == "POST" and form.is_valid():
        # Process the data in form.cleaned_data
        return HttpResponseRedirect('/thanks/')

    return render(request, 'contact.html', {
        'form': form,
    })
Say Thanks
Respond

5 Responses
Add your response

1297
61e84e983b8f1531a755a86b7d46cf43

That's not exactly DRY, since there is a boolean test twice on request.POST.
Python is about being explicit and easy to read, not about being short and obscure - that sort of stuff is what Perl handles :) Therefore, I would prefer the first code block.
For more, please refer to the Zen of Python - type "import this" in your python shell.

over 1 year ago ·
1575
Bfd59355c6fa6b7b7e23c351249525a8

Wrote about how to handle forms, that will allow easier customize your view for users of your app - https://coderwall.com/p/ypgd1q. Another thing - you don't need request.method == "POST", except cases when your form is initially already valid.

over 1 year ago ·
3821
4f776ee53d980b0c7eac4814b7d327bf

No need for the “request.method == "POST"”

over 1 year ago ·
4100
7c6c961a2114495b25d5f59ca50a7931

The second code has a bug. If the form contains only checkbox fields, when submitted and none of them are checked, the request.POST variable will be an empty dictionary, evaluated as False.

So, the form will be initialized with None (and consequently unbound). So the is_valid will be always False, even if the form is valid.

over 1 year ago ·
11145
258be2ca1a8c0b090d90aa6e9de7cc48

That second snippet is really bad. Hard to read, contains a bug as rennerocha notes, not dry cause there are essentially two checks if the request is a POST request. Don't ever use it, please. The Django way is the correct one or use class based views.

over 1 year ago ·
Awesome Job

82f9d2b0 ffd5 11e7 9bd5 132a929e586d
Senior QA Engineer
·
San Francisco Bay Area
·
Full Time