Django FormView没有表单上下文

时间:2013-10-30 15:41:52

标签: django view django-templates formview django-context

定义FormView派生类时:

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)

我预计不需要行context['form'] = MyForm,因为form_class已定义,但如果没有,{{ form }}则不会传递给模板。
我做错了什么?

2 个答案:

答案 0 :(得分:14)

在上下文中,form应该是实例化的表单,而不是表单类。定义form_class与在上下文数据中包含实例化表单完全不同。

对于您提供的示例,我认为您最好覆盖get_context_data而不是get

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

答案 1 :(得分:0)

覆盖 get_context_data,context['form'] 取自 SomeForm,并更改为 form_1,您可以在模板中作为 form_1 使用

class Something(generic.CreateView):
        template_name = 'app/example.html'
        form_class = forms.SomeForm
        model = models.SomeModel
    
        def get_context_data(self, **kwargs):
            context = super(Something, self).get_context_data(**kwargs)
            context["form_1"] = context["form"]
            context["form_2"] = forms.SomeForm2(**self.get_form_kwargs())
            return context