【问题标题】:Looking for Django Class based views and having multiple forms on a single page examples寻找基于 Django 类的视图并在单个页面示例上有多个表单
【发布时间】:2012-08-07 03:53:13
【问题描述】:

我一直在寻找如何使用较新的基于 Django 类的视图方法在一个页面上显示 2 个独特的表单。

任何人都可以参考任何东西吗?或者提供一个基本的例子。 Google 不是我的“朋友”。

【问题讨论】:

    标签: django forms class


    【解决方案1】:

    关键是您甚至不必使用FormView 子类之一来处理表单。您只需添加用于手动处理表单的机制。如果您确实使用了FormView 子类,它只会处理 1 且仅处理 1 个表单。因此,如果您需要两种表格,您只需手动处理第二张表格。我使用DetailView 作为基类只是为了表明您甚至不必从FormView 类型继承。

    class ManualFormView(DetailView):
        def get(self, request, *args, **kwargs):
            self.other_form = MyOtherForm()
            return super(ManualFormView, self).get(request, *args, **kwargs)
    
        def post(self, request, *args, **kwargs):
            self.other_form = MyOtherForm(request.POST)
            if self.other_form.is_valid():
                self.other_form.save() # or whatever
                return HttpResponseRedirect('/some/other/view/')
            else:
                return super(ManualFormView, self).post(request, *args, **kwargs)
    
        def get_context_data(self, **kwargs):
            context = super(ManualFormView, self).get_context_data(**kwargs)
            context['other_form'] = self.other_form
            return context
    

    【讨论】:

      猜你喜欢
      • 2016-12-05
      • 2014-01-11
      • 1970-01-01
      • 1970-01-01
      • 2015-01-30
      • 1970-01-01
      • 2018-08-31
      • 2014-07-04
      • 2015-07-10
      相关资源
      最近更新 更多