基于Django类的视图和表单集

时间:2012-10-15 07:19:15

标签: django

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

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)

这样可以很好地添加行,但不幸的是,每次用户添加新行时它也会添加一个新对象。我应该如何/在哪里短路这个对象添加行为?

1 个答案:

答案 0 :(得分:1)

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

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方法:

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