Django class based views and formsets

后端 未结 1 924
离开以前
离开以前 2021-01-28 16:29

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 whe

1条回答
  •  一向
    一向 (楼主)
    2021-01-28 17:16

    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)
    

    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
    

    0 讨论(0)
提交回复
热议问题