基于Django类的视图和formets [英] Django class based views and formsets

查看:111
本文介绍了基于Django类的视图和formets的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基于类的视图,名为 OrganizationsCreateView ,其中包含一个作为该窗体的实例变量附加到模型窗体的表单。当用户输入数据时,这样工作正常 - 新对象创建正常。当用户想要添加额外的行到表单集时,我有一个提交按钮,触发条件在CreateView的发布方法:

I have a class-based view called OrganizationsCreateView that includes a formset attached to a model form as an instance variable of that form. This works fine when the user enters data -- a new object is created fine. When the user wants to add additional rows to the formset, I have a submit button that triggers a conditional in the CreateView's post method:

def post(self,request,*args,**kwargs):
    if 'add_email' in request.POST:

        cp = request.POST.copy()
        cp['emails-TOTAL_FORMS'] = int(request.POST['emails-TOTAL_FORMS']) + 1
        self.initial_emails = cp

    return super(OrganizationsCreateView,self).post(request,*args,**kwargs)

这样添加行很好,但不幸的是它也添加每次用户添加新行时都会有一个新对象。

This adds rows just fine, but unfortunately it also adds a new object each time the user adds a new row. How/where should I short-circuit this object adding behavior?

推荐答案

在研究Django基于类视图的响应流程之后,这里是我使用的post方法,它的效果很好:

After studying the response flow of Django's class-based views, here is the post method I am using which works great:

def post(self,request,*args,**kwargs):
    if 'add_email' in request.POST:
        # Set the object like BaseCreateView would normally do
        self.object = None

        # Copy the form data so that we retain it after adding a new row
        cp = request.POST.copy()
        cp['emails-TOTAL_FORMS'] = int(request.POST['emails-TOTAL_FORMS']) + 1
        self.initial_emails = cp

        # Perform steps similar to ProcessFormView
        form_class = self.get_form_class()
        form = self.get_form(form_class)

        # Render a response identical to what would be rendered if the form was invalid
        return self.render_to_response(self.get_context_data(form=form))

    return super(OrganizationsCreateView,self).post(request,*args,**kwargs)

另一个重要的部分是 get_form_kwargs 方法:

The other important part is the get_form_kwargs method:

def get_form_kwargs(self):
    kwargs = super(OrganizationsCreateView,self).get_form_kwargs()
    kwargs['initial_emails'] = self.initial_emails
    return kwargs

这篇关于基于Django类的视图和formets的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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