django M2M保存(POST后)

时间:2015-05-26 19:10:41

标签: python django formset inline-formset m2m

我在表单中有一个表单,允许用户选择他们想要包含的电子邮件列表(通过复选框)。该列表来自查询:

form.fields['email_list'].queryset = EmailList.objects.filter(is_active=True, is_visible=True)

还有一些用户无法看到的电子邮件列表(is_visible=False)。用户无法看到这些记录,但如果管理员已将用户添加到其中一个列表(通过“管理”面板),那么这些列表需要保存,并且用户对列表中的任何更改都可以看到。

在我看来,我需要从POST获取对象并将查询的输出(... is_visible=False)附加到它。然后我可以保存它,所有这些M2M记录都将被保存。但是,我无法让它发挥作用。

formset的视图如下所示:

        FamilyInlineFormSet = modelformset_factory(Family, extra=0, formset=FamilyBaseFormSet)
FamilyMemberInlineFormSet = modelformset_factory(FamilyMember,
    extra=0, formset=FamilyMemberBaseFormSet)

if request.method == "POST":
    family_formset = FamilyInlineFormSet(request.POST,  request.FILES,
            queryset=Family.objects.filter(id=request.user.family.id), prefix='f')
    family_member_formset = FamilyMemberInlineFormSet(request.POST, request.FILES,
            queryset=FamilyMember.objects.filter(family=request.user.family.id), prefix='fm')
    if family_formset.is_valid() and family_member_formset.is_valid():

        ####### HERE IS WHERE THE CODE SHOULD GO, I BELIEVE #############

        family_formset.save()
        family_member_formset.save()
        return redirect('/school/thanks/')
else:
    family_formset = FamilyInlineFormSet(queryset=Family.objects.filter(id=request.user.family.id), prefix='f')
    family_member_formset = FamilyMemberInlineFormSet(queryset=FamilyMember.objects.filter(family=request.user.family.id), prefix='fm')

context = RequestContext(request,{
    'family_formset': family_formset,
    'family_member_formset': family_member_formset,
})
return render_to_response("school/family/manage_family_members.html", context)

以下是模型文件中的条目:

    email_list = models.ManyToManyField('EmailList', verbose_name="Email Lists", blank=True, null=True)

有人能指出我如何实现这个目标吗?

0 个答案:

没有答案