0

我有一个名为的基于类的视图OrganizationsCreateView,它包括一个附加到模型表单的表单集作为该表单的实例变量。当用户输入数据时,这很好用——一个新的对象被创建得很好。当用户想要向表单集添加额外的行时,我有一个提交按钮,它在 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)

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

4

1 回答 1

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
于 2012-10-16T00:33:13.413 回答