oebfare

Changing the ModelChoiceField QuerySet

One question that keeps on showing up on IRC is asking how to change the choices in a ModelChoiceField. This applies to a ModelMultipleChoiceField as well. Here is how to accomplish this:

from django import newforms as forms
from django.contrib.auth.models import User

class ComplaintForm(forms.Form):
    user = forms.ModelChoiceField(queryset=User.objects.none())
    message = forms.CharField(widget=forms.Textarea())

    def __init__(self, *args, **kwargs):
        super(ComplaintForm, self).__init__(*args, **kwargs)
        self.fields["user"].queryset = User.objects.filter(is_staff=False)

The trick here is that we can pass in an EmptyQuerySet in the form field definition then change it later. This is a bad example since you could have simply defined the queryset in __init__ in the form field definition. The nice thing about this is that __init__ is called within a view so you can pass parameters to it to filter the queryset based on data in the HttpRequest.

Entry Details

Published: Feb 23, 2008 at 6:01 PM

© 2007 - 2008 Brian Rosner