Django FormView没有表单上下文

ton*_*njo 13 django formview view django-templates 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)
Run Code Online (Sandbox Code Playgroud)

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

Ala*_*air 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
Run Code Online (Sandbox Code Playgroud)

  • 使用`FormView`时,[`form_class`](https://docs.djangoproject.com/en/dev/ref/class-based-views/mixins-editing/#django.views.generic.edit.FormMixin. form_class)定义要实例化的表单类型.`get`方法实例化一个表单,并将其包含在上下文中.由于你要覆盖`get`,你还需要在上下文中包含`form`.因为你似乎重写了`get`方法来为模板上下文添加一个额外的变量,所以我建议覆盖`get_context_data` - 这样你就不必担心`get`方法所做的其他事情了. (4认同)
  • 如果你不重写`get`,你*不需要那行.如果您这样做,那么您将阻止默认实现包含表单,因此您当然需要自己包含它. (3认同)