以formset添加到M2M

时间:2015-07-22 12:58:46

标签: django django-forms m2m

我正在尝试添加到以formset提交的M2M字段。添加的记录未添加。这是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()

get_admin()查询返回以下内容:

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

我认为应该是这样的: - get_admin()检索此用户在数据库中保存的记录。 - 然后将这些记录添加到提交的表单中。 - 保存表单时,M2M代码会删除所有这些记录。 - 然后,M2M代码会添加此表单中包含的所有M2M记录。 - 因为我在保存之前将记录添加到表单中的get_admin(),这些记录应该添加到数据库中。

我发现的是这些记录没有被保存。所有保存的内容都是用户在提交表单之前所做的选择。

1 个答案:

答案 0 :(得分:0)

解决。

    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)