0

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 when the user enters data -- a new object is created fine. When the user wants to add additional rows to the formset, I have a submit button that triggers a conditional in the CreateView's post method:

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)

This adds rows just fine, but unfortunately it also adds a new object each time the user adds a new row. How/where should I short-circuit this object adding behavior?

Erik
  • 7,479
  • 8
  • 62
  • 99

1 Answers1

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
  • 7,479
  • 8
  • 62
  • 99