[Fixed]-Formset: saving models won't work

1👍

✅

Ok, with a fresh head I looked at my code, and then it occurred to me. I wanted to make sure that the entry and each shift are built correctly first, and then only save them if they don’t violate any rules. So as you can see above: I’m saving both with commit=False. That means however that entry has not been assigned a primary key yet. The primary key is what the ForeignKeyField on my shift model needs. That’s why Django failed saving it.
I changed the order of the method somewhat. This is the working code:

def post(self, request, ordinal=None, *args, **kwargs):
    form    = AddWorkDay(data=request.POST)
    formset = ShiftFormSet(data=request.POST)
    errors  = []
    shifts  = []

    if form.is_valid() and formset.is_valid():
        # Build entry.
        entry       = form.save(commit=False)
        entry.owner = request.user
        errors.extend(entry.validate(request.user))

        # Build shift.
        for form in formset:
            shift       = form.save(commit=False)
            shifts.append(shift)
            errors.extend(shift.validate(request.user))

        # If there are no errors, save the entry ans it's shifts.
        if len(errors) == 0:
            entry.save()
            for shift in shifts:
                shift.entry = entry
                shift.save()
            return HttpResponseRedirect(reverse('time_manager:index'))

    return render(request, self.template_name, {'form': form, 'formset': formset, 'errors': errors, 'shifts': shifts, 'entry': entry})

Notice how entry is saved for the second time (without commit=False) and then assigned to shift.

Leave a comment