Django forms: passing variables to a modelchoicefield

So I came across the problem of needing to filter my Django ModelChoiceField queryset by a variable in my view. Specifically I needed to pass the current selected state to the ModelChoiceField queryset. The best way I found to do this is to initialize the form with my state var in the initial:

state = 'OH'
form = LocationForm(initial={'state':state})

After that, instead of creating the field the traditional way, you can append the field to the self.fields dictionary within the init, enabling you to pass the initial state variable into the queryset of the field. Here is my form:

class LocationForm(forms.Form):

    def __init__(self, *args, **kwargs):
        super(LocationForm, self).__init__(*args, **kwargs)
        self.fields.insert(len(self.fields)-1, 'location',
                           forms.ModelChoiceField(queryset=Location.objects.filter(state=self.initial['state'])))

    first_name = forms.CharField(50, label="First Name")
    last_name = forms.CharField(50, label="Last Name")
    address = forms.CharField(60, label="Street Address")
    city = forms.CharField(40, label="City")
    state = USStateField()
    zip = USZipCodeField()

Self.fields is a Django SortedDict, and it’s insert method takes the index to insert to, the key, and the value.

Leave a Reply

Your email address will not be published. Required fields are marked *