在单个页面示例中查找基于Django类的视图并具有多个表单 [英] Looking for Django Class based views and having multiple forms on a single page examples

查看:95
本文介绍了在单个页面示例中查找基于Django类的视图并具有多个表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



任何人都可以引用任何内容吗?

我一直在寻找一个很长的远程,如何使用更新的基于Django类的视图方法在一个页面上显示2个独特的表单。或者提供一个基本的例子。 Google不是我的朋友。

解决方案

关键是你甚至不必使用 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 * args,** kwargs):
self.other_form = MyOtherForm(request.POST)
如果self.other_form.is_valid():
self.other_form.save()#或whatever
return HttpResponseRedirect('/ some / other / view /')
else:
return super(ManualFormView,self).post(request,* args,** kwargs)
b $ b def get_context_data(self,** kwargs):
context = super(ManualFormView,self).get_context_data(** kwargs)
context ['other_form'] = self.other_form
返回上下文


I have been looking long and far for how to have 2 unique forms displayed on one page using the newer Django class based views method.

Can anybody reference anything? Or provide a basic example. Google is not being my "friend" for this.

解决方案

The key is that you don't even have to use one of the FormView subclasses to process forms. You just have to add the machinery for processing the form manually. In the case where you do use a FormView subclass, it will only process 1 and only 1 form. So if you need two forms, you just have to handle the second one manually. I'm using DetailView as a base class just to show that you don't even have to inherit from a FormView type.

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

这篇关于在单个页面示例中查找基于Django类的视图并具有多个表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆