【问题标题】:How to specify the name of the form variable used in the template of a FormView? (object_context_name for forms)如何指定 FormView 模板中使用的表单变量的名称? (表单的对象上下文名称)
【发布时间】:2013-03-14 21:37:37
【问题描述】:
from forms import MyContactForm
from django.views.generic.edit import FormView 

class MyFormView(FormView):
    template_name = 'my_forms.html'                                      
    form_class = MyContactForm  
    success_url = '/thanks/' 

在我的模板中,表单是这样调用的:

{{ form }}

但我怎么能这样称呼它:

{{ my_contact_form }}?

这将是等效于object_context_name(对于模型)的形式。

【问题讨论】:

标签: django django-class-based-views


【解决方案1】:

你可以覆盖get_context_data:

class MyFormView(FormView):
    template_name = 'my_forms.html'                                      
    form_class = MyContactForm  
    success_url = '/thanks/' 

    # from ContextMixin via FormMixin    
    def get_context_data(self, **kwargs):
        data = super(MyFormView, self).get_context_data(**kwargs)

        data['my_contact_form'] = data.get('form')

        return data

【讨论】:

  • 当您想使用多个表单时,您知道该怎么做吗?我只是想将它们中的每一个传递给一个数据键,然后删除form_class。但是当我这样做时,我会得到一个TypeError, NoneType is not callable
  • 您只能提交一份表格。 generic.edit.FormView 管理一个表格。查看source of FormMixin and ProcessFormView:您必须覆盖getform_invalid 才能呈现所有表单,并且您必须覆盖post 以确定提交的表单并处理它。在这一点上,我认为你不应该继承 FormView
  • 检查stackoverflow.com/questions/6276398/…,尤其是对已接受答案的第二次更新。
猜你喜欢
  • 2011-09-01
  • 2017-01-29
  • 2011-06-26
  • 2013-06-15
  • 2017-07-13
  • 2017-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多