2012-10-15 90 views
0

我有一個名爲OrganizationsCreateView的基於類的視圖,該視圖包含附加到模型表單的表單作爲該表單的實例變量。這在用戶輸入數據時工作正常 - 新對象創建正常。當用戶想要更多的行添加到表單集,我有一個提交按鈕,觸發條件在CreateView的的帖子方法:Django基於視圖和表單集

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

學習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