Last Updated: September 09, 2019
·
1.742K
· ilblackdragon

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.

2 Responses
Add your response

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

over 1 year ago ·

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

over 1 year ago ·