Working Ninja
2018-09-26T20:30:58
Filtering a Prepopulated ModelForm QuerySet in Django

By default, a ModelForm is populated with all its objects from the database. Sometimes it's desirable to limit these results as they are returned to the view. After setting up our ModelForm (forms.py) there is only one thing we need to do to make this happen. Within our view (views.py), we update the queryset as follows:

# forms.py
class PollForm(ModelForm):
    class Meta:
        model = Poll
        fields = ('question',)

# views.py
form = PollForm()
form.fields['question'].queryset = Poll.objects.filter(question__startswith="How")

This will filter Polls that start with "How".

Source: http://www.wkoorts.com/wkblog/2009/08/10/pre-populate-django-modelform-with-specific-queryset/