django FormView

django FormView

  • Django comes with a reusable class based views and FormView is one of them.
  • A view for displaying a form, and rendering a template response.

When and Why to use FormView?

  • it can be used when we a functionality to submit the forms
  • it allows us to quickly render the page with a form with less code.
  • we can render forms with conditionals also by overriding few methods in the FormView when we have requirement for a conditional rendering of form.

UML diagram for FormView

django template view

  • Above is the UML diagram for FormView.
  • It inherits the classes BaseFormView, FormMixin, TemplateResponseMixin, ProcessFormView, ContextMixin, View.
  • we can check the code for FormView at github.
  • It comes with request methods GET and POST.
  • GET method will render the form with context
  • POST method will post the data to the server and renders the form again if has any errors otherwise it will redirect it to the success_url mentiond in the FormView.
  • can override get_context_data to send extra context to the template.
  • can override get_form_class for conditional rendering of form
  • can override get_success_url for conditional successful redirect.
  • can override form_valid and form_invalid whenever required.

Usage of FormView in django

Let's implement the contact us page with FormView.


        <h1> Contact Us</h1>
        <form action="" method="post">{% csrf_token %}
            {{ form.as_p }}
            <input type="submit" value="Submit" />

from django import forms

class ContactForm(forms.Form):
    name = forms.CharField()
    message = forms.CharField(widget=forms.Textarea)

    def send_email(self):
        # send email using the self.cleaned_data dictionary

from myapp.forms import ContactForm
from django.views.generic.edit import FormView

class ContactView(FormView):
    template_name = 'contact_us.html'
    form_class = ContactForm
    success_url = '/thanks/'

    def form_valid(self, form):
        # This method is called when valid form data has been POSTed.
        # It should return an HttpResponse.
        return super(ContactView, self).form_valid(form)
  • It's that simple to implement form submission functionality with the help of FormView otherwise it will need to write our own code which will take more development time.
  • By using django generic views we can rapidly reduce the development time.
  • Read the django github repo code to understand more about the django generic views and what to override and when.