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.
