我正在使用ModelMultipleChoiceField做某事,但出现一条错误消息:
AttributeError at /auth_users/
'MultipleChoiceField' object has no attribute 'all'
我的表单是:
class AuthUserCheckbox(forms.Form):
choice = forms.ModelMultipleChoiceField(queryset=User.objects.none(), widget=forms.CheckboxSelectMultiple, required=True)
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user')
user_email = self.user.email.split('@')[1]
super(AuthUserCheckbox, self).__init__(*args, **kwargs)
self.fields['choice'].queryset = forms.MultipleChoiceField(
choices=[
(i.email, i.email)
for i in User.objects.filter(
is_active=False,
email__icontains=user_email
)
]
)
我的视图是:
@login_required
def auth_users(request):
if request.method == 'POST':
form = AuthUserCheckbox(request.POST, user=request.user)
if form.is_valid():
AuthUserCheckbox.auth_users(form)
return render(request, 'todoapp/success.html')
else:
return HttpResponse('<h3>Authorization failed</h3>')
return render(request, 'todoapp/auth_users.html', context={'form': AuthUserCheckbox(user=request.user)})
我要去哪里错了?这个错误困扰着我很多。
答案 0 :(得分:2)
您为MultipleChoiceField
的查询集分配了ModelMultipleChoiceField
,但是您需要分配查询集。
例如这样的
class AuthUserCheckbox(forms.Form):
...
def __init__(self, *args, **kwargs):
...
self.fields['choice'].queryset = User.objects.filter(
is_active=False,
email__icontains=user_email,
)