[Answer]-Django class based views and formsets

1👍

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
👤Erik

Leave a comment