ypgd1q
Last Updated: February 25, 2016
·
1.519K
· ilblackdragon
Bfd59355c6fa6b7b7e23c351249525a8

Even better way to handle Django forms

There is a pro tip "Better Way To Initialize Django Forms", which is a good tip how to handle forms in less code, but don't show how to make your view more customizable.

Instead of common way:

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,
    })

I usually do next:

def contact(request, form_class=ContactForm, template_name='app_name/contact.html'):
    form = form_class(request.POST or None)
    if form.is_valid():
        form.save()
        return redirect('thanks_url')
    return TemplateResponse(request, template_name, {
        'form': form,
    })

Positive sides are:

  • formclass and templatename allows to customize your view without forking your app - just by manipulating urls in special ext app.
  • Moving processing of form data to form.save(), allows as well to customize processing by inheritance of form class, not by rewriting all view function
  • use redirect for redirecting to specific url name, not url. Urls are tend to change over time.
  • TemplateResponse - returns lazy object, that will be rendered later, and can be customized by decorators or middlewares.
Say Thanks
Respond

2 Responses
Add your response

4103
A0b68023e272145aa688cc71a555f1db

I'm going to update my Django forms right now....OK, maybe after I drink a Tab :)

over 1 year ago ·
5413

Or you could use Class based FormView.. much nicer :)

over 1 year ago ·