Saving formset saves a bunch of blank forms

+1 vote
asked Feb 10, 2017 by ruth-young

So I have a view where I can add as many forms as the user wants with an add row function and then click save. The page displays existing forms and allows you to add new ones.

When I save the first one it all works fine. Then as I continue to save, it saves the new record PLUS a number of blank records, the number being equal to the number of forms we see on the page (existing + the number you are trying to add).

I have allowed fields to be blank because I needed to populate some fields in the view. Without this I was getting validation errors when i ran a False commit to then populate fields and save.

Here is my view - well two views because I didn't want to Redirect to another page.

def timesheet(request, timesheet_id):
    # do some stuff
    # This displays the existing records
    TimeInlineFormSet = inlineformset_factory(TimeSheet, Time, exclude=('timesheet_id',), extra=0, formset=CustomInlineFormSet)
    # This allows addition of new records
    NewTimeFormSet = modelformset_factory(Time, form=TimeForm, formset=RequiredFormSet)
    existing_formset = TimeInlineFormSet(instance=timesheet)
    newtime_formset = NewTimeFormSet()
    #render the timesheet

#and this is where I save
def create_time(request):
    #some stuff, get timesheet id 
    NewTimeFormSet = modelformset_factory(Time, form=TimeForm, formset=RequiredFormSet)
    if request.method == 'POST':
        newtime_formset = NewTimeFormSet(request.POST, request.FILES)
        if newtime_formset.is_valid():
            for orange in newtime_formset:
                    obj = orange.save(commit=False)
                    if obj.add_row == True:
                        obj.add_row = False
                        # set some fields
                        obj.save()
        else:
            print "new row not valid"
        return HttpResponseRedirect(reverse("tande:timesheet", kwargs={"timesheet_id": timesheet_object}))

The add row field is default True, I tried to do this to avoid saving existing records as I set it to False when it's saved.

Thanks

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...