Django FormView does not have form context

tonjo picture tonjo · Oct 30, 2013 · Viewed 13.6k times · Source

When defining a FormView derived class:

class PrefsView(FormView):
    template_name = "prefs.html"
    form_class = MyForm         # What's wrong with this?
    def get(self,request):
        context = self.get_context_data()
        context['pagetitle'] = 'My special Title'
        context['form'] = MyForm    # Why Do I have to write this?
        return render(self.request,self.template_name,context)

I expected the line context['form'] = MyForm was not needed, since form_class is defined, but without it {{ form }} is not passed to template.
What I'm doing wrong?

Answer

Alasdair picture Alasdair · Oct 30, 2013

In the context, form should be the instantiated form, not the form class. Defining the form_class is completely separate from including the instantiated form in the context data.

For the example you've given, I think you'd be better to override get_context_data instead of get.

def get_context_data(self, **kwargs):
    context = super(PrefsView, self).get_context_data(**kwargs)
    context['pagetitle'] = 'My special Title'
    return context