Martin Trigaux
Martin Trigaux

Reputation: 5401

Check prefiled formset and remove empty

On my reservation site for an event, I want to allow people to manage their guests list. I represent the reservation with a Registration model and the guests with a Guest model using a foreign key invited = models.ForeignKey(Registration).

I used a modelformset_factory to create a set of forms to record each guest at the registration. Now, to update this list, I use the following code:

registr = Registration.objects.get(id=postid) # get the registration
GuestFormSet = modelformset_factory(Guest,
                       extra=MAXGUESTS,
                       exclude=('invited',)) # generate MAXGUESTS Guest forms
guests = GuestFormSet(request.POST) # put the submited formset
if guests.is_valid():
    guests = guests.save(commit=False)
    for guest in guests:
        guest.invited = registr
        guest.save()

This works (+/-) to update the fields of an existing guest or to ass one but now I want to have the possibility to delete guest (simply by emptying the form of the guest). The problem is that I have an error "This field is required." for each field of the guest I want to remove.

Any idea how I can do that ?

Thank you


Solution

registr = Registration.objects.get(id=postid) # get the registration
maxg = max(0,MAXGUESTS - len(Guest.objects.filter(invited=registr))) # MAXGUEST form, existing guests included
GuestFormSet = modelformset_factory(Guest,
                       extra=maxg,
                       can_delete=True,
                       exclude=('invited',)) # generate MAXGUESTS Guest forms
guests = GuestFormSet(request.POST) # put the submited formset

if guests.is_valid():
    # create new guests
    guests = guests.save(commit=False)
    for guest in guests:
        guest.invited = registr
        guest.save()

    # get the guests from the updated database
    maxg = max(0,MAXGUESTS - len(Guest.objects.filter(invited=registr)))
    GuestFormSet = modelformset_factory(Guest, extra=maxg, can_delete=True, exclude=('invited',))
    guests = GuestFormSet(queryset=Guest.objects.filter(invited=registr))

Upvotes: 0

Views: 1811

Answers (1)

Marius Grigaitis
Marius Grigaitis

Reputation: 2520

In django I see that modelformset_factory accepts can_delete parameter: https://code.djangoproject.com/browser/django/trunk/django/forms/models.py#L664

You can see can_delete mentioned here: https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#inline-formsets

Upvotes: 1

Related Questions