Search code examples
djangodjango-formsm2m

Add to M2M in formset


I am trying to add to an M2M field submitted in a formset. The added records are not being added. Here is the views.py

if family_member_formset.is_valid():
    for form in family_member_formset:
        fmform = form.save(commit=False)
        # This query should return a list of "email lists" that should be
        # added to the form before it is submitted.
        matches = fmform.email_list.get_admin()
        for ae in matches:
            fmform.email_list.add(ae)
        fmform.save()
        form.save_m2m()

The get_admin() query returns the following:

>>> matches
[<EmailList: Knee-mail>, <EmailList: Student Council>, <EmailList: Co-o>,<EmailList: High School>, <EmailList: General Homeschool Info>]

What I believe happens should be this: - get_admin() retrieves the records that this user has saved in the database. - these records are then added to the submitted form. - when the form is saved, the M2M code deletes all of these records. - the M2M code then adds all M2M records that are included in this form. - since I added the records to get_admin() to the form before it was saved, these records should be added to the database.

What I'm finding is that these records are not being saved. All that is being saved is the selection that the user made before submitting the form.


Solution

  • Solved.

        if family_member_formset.is_valid():
            for form in family_member_formset:
                fmform = form.save(commit=False)
                matches = fmform.email_list.get_admin().all()
                # Not sure if I need this but it ensures that
                # the database records are actually retrieved before
                # the records are deleted in the save_m2m call
                elist=[]
                for e in matches:
                    elist.append(e)
                fmform.save()
                form.save_m2m()
                # Add entries AFTER the M2M records are saved
                for ae in elist:
                    fmform.email_list.add(ae)