Django ModelChoiceField表单格式不正确

时间:2014-07-03 14:18:31

标签: django python-2.7 django-forms django-views

我使用以下表格来创建问题。这里的community是用户所属的特定社区。

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。 该对象正在正确呈现,但我无法在下拉列表中看到任何数据。 为什么会出现这个问题,应该采取什么措施来解决这个问题。

1 个答案:

答案 0 :(得分:3)

community字段使用ModelChoiceField。常规ChoiceFieldchoices作为参数,而不是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)