django localflavor USStateSelect() inital value

736 Views Asked by At

I'm trying to use the django localflavor widget USStateSelect() in a form, but I want the widget to have Nebraska selected by default. The Widget only accepts an attrs arg, so I'm trying to understand what attributes I have to set to get the desired result. Here's what I've got in my forms.py:

state = forms.CharField(widget=USStateSelect(attrs={'value':'NE'}))

This is the docs for the HTML select element: http://www.w3.org/html/wg/drafts/html/CR/forms.html#the-select-element

This is the docs for localflavor: https://django-localflavor.readthedocs.org/en/latest/_modules/localflavor/us/forms/

<option value="NE" selected>Nebraska</option>

This is what I need to have in my html, but I can't figure out what the attrs dict needs to contain to achieve this result. I've tried adding 'selected':'selected' and 'class':'selected' to the dict, but that's not doing it.

I've seen a number of people asking how to add an empty option, but no one seems to want to make it default to a specific state. Any ideas are welcome.

Thanks,

Anthony

1

There are 1 best solutions below

0
On BEST ANSWER

You can set the initial value like so:

state = forms.CharField(widget=USStateSelect(), initial='NE')

or you can set it when you instantiate the form:

form = ExampleForm(initial={'state': 'NE'})