February 8th, 2010 posted by Bender Rodríguez
The Django folks fixed the US State field in local flavors, making it a CharField, which addressed a few oddities in its behavior.
I recently created a form that needed to display the US states as select field, which Django makes quite easy using the local flavors add on. The entire process was rather confusing at first. Basically, you do not use the us.forms.USStateField class, which does not provide you with a select field, nor do you use the us.forms.USStateSelect, which you would think would be the obvious choice.
When I tried to use the us.forms.USStateSelect in my forms definition class, there was no blank option of ('', '----------') so people do not accidentally forget to change the state and we would have a bunch of submissions for Alabama.
Instead, you have to use the us.models.USStateField class from the models package. Obviously, you use USStateField in your models.py class definition, not in your forms classes. In my model, I have:
address = models.CharField(max_length=255, verbose_name = 'Address') city = models.CharField(max_length=128, verbose_name = 'City') state = USStateField() zip = models.CharField(max_length=10, verbose_name = 'Zip code')
You use USStateField() instead of the models.CharField. I am not certain why Django still has the
us.forms.USStateSelect, but perhaps someone still has a need for it.
0 Comments, 0 trackbacks (Trackback URL)
"Nationalism is an infantile disease, the measles of mankind"
Albert Einstein