Django - form valid method

Hello here is a create view from the Django documentation.

class ContactView(FormView):
    template_name = 'contact.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.
        form.send_email()
        return super().form_valid(form)

I am confused on what the last line in this function actually does. The docs state that it returns a HTTP response, however many other sources state it validates the data or something similar to this. What actually are the purposes of this last line in form_valid? Thanks.

[Note: I’ve seen where you’ve asked a couple similar questions here about different aspects of the CBVs. This reply really applies to all.]

The best way to understand the generic CBVs is to read through the source code, while looking at the Classy Class Based Views documentation site and follow through the logic of the view.

Remember that a CBV is referenced from your urls using the “as_view” method. That’s where the flow starts that you’re interested in.

Just take your time and realize going in that there’s a lot going on. There are a lot of methods that get called along the way, each one (generally) providing a hook that you can use to override the pre-defined functionality. (These hooks work because methods you define in your subclass would be called before the same-named methods in the parent classes.)

So looking at the “form_valid” method of the CreateView, you can see that the default method ends up calling the form_valid method in ModelFormMixin which then ends up calling form_valid in FormMixin, which returns an HttpResponseRedirect object. In your case above, you’re sending an email, and then “going up the chain” to invoke the same method above you in the inheritance hierarchy.

Ken