我的应用程序有一个Family模型,其中包含FamilyMember模型的外键。 FamilyMember模型是我用于身份验证的模型。
我正在使用inlineformset_factory来允许用户修改他所属的Family的所有FamilyMember记录。我想要做的是修改" email_list"的查询集。为每个家庭成员。 queryset过滤器应基于该特定系列成员的is_staff标志。请注意,它不应该基于登录用户的is_staff。这意味着该系列的一些家庭成员将使用一个查询,而其他家庭成员将使用不同的查询。
# FORM
class FamilyMemberForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(FamilyMemberForm, self).__init__(*args, **kwargs)
if self:
self.fields["email_list"].queryset = EmailList.objects.filter(is_active=False)
else:
self.fields["email_list"].queryset = EmailList.objects.filter(is_active=True)
class Meta:
model = FamilyMember
fields = ['first_name', 'middle_name', 'last_name', ... 'email_list']
FamilyMemberFormset = inlineformset_factory(Family, FamilyMember, can_delete=False, form=FamilyMemberForm, extra=0)
# VIEW
def manage_family_member(request):
email_list_description = EmailList.objects.filter(is_active=True)
f = get_object_or_404(Family, id=request.user.family.id)
form = FamilyForm(instance=f)
fm = FamilyMemberFormset(instance=f)
if request.method == 'POST':
form = FamilyForm(request.POST, instance=f)
if form.is_valid():
f = form.save(commit=False)
fm = FamilyMemberFormset(request.POST, request.FILES, instance=f)
if fm.is_valid():
f.save()
fm.save()
return redirect('/school/thanks/')
context = RequestContext(request,{
'email_list_description': email_list_description,
'form': form,
'family_member_formset': fm,
})
return render_to_response("school/family/manage_family_members.html", context)
答案 0 :(得分:1)
class FamilyMemberForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(FamilyMemberForm, self).__init__(*args, **kwargs)
instance = kwargs.pop('instance', None)
if instance.is_staff:
self.fields["email_list"].queryset = EmailList.objects.filter(is_active=False)
else:
self.fields["email_list"].queryset = EmailList.objects.filter(is_active=True)
当然,我不会在实际查询中使用“is_active = False”和“is_active = True”,但它为我提供了一种非常快速的方法来测试我的代码。
谢谢!