Vinay Chandra
Vinay Chandra

Reputation: 552

Django ModelChoiceField in forms not displaying properly

I use the following forms for creating a question. The community here is a specific community a user belongs to.

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)

The corresponding view is this.

def add_question(request):
    if request.user.is_authenticated():
        form = Question(user=request.user)
        context = {
            'form': form
        }
        return render(request, 'question.html', context)

I am calling form.as_table appropriately in the template file. The object is being rendered properly but I cannot see any data in the dropdown. Why is this problem occurring and what should be done to solve this.

Upvotes: 2

Views: 1811

Answers (1)

Alasdair
Alasdair

Reputation: 309099

Use a ModelChoiceField for your community field. A regular ChoiceField takes choices as an argument, not queryset.

When you set the queryset attribute in your __init__ method, assign a queryset to it, not a form field.

Putting it altogether, you have:

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)

Upvotes: 3

Related Questions