Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django FormView does not have form context

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?

like image 332
tonjo Avatar asked Oct 30 '13 15:10

tonjo


Video Answer


1 Answers

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
like image 124
Alasdair Avatar answered Sep 28 '22 06:09

Alasdair