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:

  1. state = ‘OH’
  2. 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:

  1. class LocationForm(forms.Form):
  2.     def __init__(self, *args, **kwargs):
  3.         super(LocationForm, self).__init__(*args, **kwargs)
  4.         self.fields.insert(len(self.fields)-1‘location’,
  5.                            forms.ModelChoiceField(queryset=Location.objects.filter(state=self.initial[‘state’])))
  6.     first_name = forms.CharField(50, label=“First Name”)
  7.     last_name = forms.CharField(50, label=“Last Name”)
  8.     address = forms.CharField(60, label=“Street Address”)
  9.     city = forms.CharField(40, label=“City”)
  10.     state = USStateField()
  11.     zip = USZipCodeField()

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

Source

Anuncios

Responder

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión / Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión / Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión / Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión / Cambiar )

Conectando a %s