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.


Comments

Nice trick. Personnaly I was using a closure for this:

def get_complaint_form(users):

class ComplaintForm(forms.Form):
user = forms.ModelChoiceField(users)
message = forms.CharField(widget=forms.Textarea())

return ComplaintForm

Posted by Batiste on Mar 18, 2008 at 2:50 AM

It appears that ModelChoiceField is now in django.newforms.models.

Posted by Kellen on Mar 23, 2008 at 8:54 AM

uDN3Ba <a href="http://zbisytaklldb.com/">zbisytaklldb</a>, [url=http://ojtbazrpskot.com/]ojtbazrpskot[/url], [link=http://fqwyickphynv.com/]fqwyickphynv[/link], http://ispkgbehtnkb.com/

Posted by oezvipfg on May 8, 2008 at 1:13 AM

Add Your Comment



Entry Details

Published: Feb 23, 2008 at 6:01 PM

© 2007 - 2008 Brian Rosner