我想在表单中使用forms.ModelMultipleChoiceField
。我知道它需要一个查询集,但是我将使用的查询集采用我通常在视图中使用request.user传递的param用户。但是这是一种形式,我如何传递request.user?我需要吗?
Entry.objects.filter(request.user)
答案 0 :(得分:2)
您应该覆盖表单的init方法:
class MyForm(forms.ModelForm):
class Meta:
model = Entry
def __init__(self, user=None, *args, **kwargs):
super(MyForm, self).__init__(*args,**kwargs)
if user is not None:
form_choices = Entry.objects.filter(user)
else:
form_choices = Entry.objects.all()
self.fields['my_mfield'] = forms.ModelMultipleChoiceField(
queryset=form_choices
)
并在您的视图中,何时实例化表单:
form = MyForm(request.user)
或
form = MyForm()