13

定义 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 }}不会传递给模板。
我做错了什么?

4

2 回答 2

17

在上下文中,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
于 2013-10-30T15:57:10.430 回答
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
于 2021-07-30T09:12:15.667 回答