我使用以下表格来创建问题。这里的community
是用户所属的特定社区。 p>
class Question(forms.Form):
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user')
super(Question, self).__init__(*args, **kwargs)
self.fields["community"].queryset = forms.ModelChoiceField(queryset=self.user.communities.all())
community = forms.ChoiceField()
description = forms.CharField(widget=forms.Textarea)
相应的观点是这样的。
def add_question(request):
if request.user.is_authenticated():
form = Question(user=request.user)
context = {
'form': form
}
return render(request, 'question.html', context)
我在模板文件中正确调用form.as_table
。
该对象正在正确呈现,但我无法在下拉列表中看到任何数据。
为什么会出现这个问题,应该采取什么措施来解决这个问题。
答案 0 :(得分:3)
对community
字段使用ModelChoiceField
。常规ChoiceField
将choices
作为参数,而不是queryset
。
在queryset
方法中设置__init__
属性时,请为其分配一个查询集,而不是表单字段。
完全放弃,你有:
class Question(forms.Form):
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user')
super(QuestionForm, self).__init__(*args, **kwargs)
self.fields["community"].queryset = self.user.communities.all()
community = forms.ModelChoiceField(queryset=Community.objects.none())
description = forms.CharField(widget=forms.Textarea)