Setting the selected value on a Django forms.ChoiceField

Viewed 174517

Here is the field declaration in a form:

max_number = forms.ChoiceField(widget = forms.Select(), 
    choices = ([('1','1'), ('2','2'),('3','3'), ]), initial='3', required = True,)

I would like to set the initial value to be 3 and this doesn't seem to work. I have played about with the param, quotes/no quotes, etc... but no change.

Could anyone give me a definitive answer if it is possible? And/or the necessary tweak in my code snippet?

I am using Django 1.0

7 Answers

Try setting the initial value when you instantiate the form:

form = MyForm(initial={'max_number': '3'})

Dave - any luck finding a solution to the browser problem? Is there a way to force a refresh?

As for the original problem, try the following when initializing the form:

def __init__(self, *args, **kwargs):
  super(MyForm, self).__init__(*args, **kwargs)   
  self.base_fields['MyChoiceField'].initial = initial_value

To be sure I need to see how you're rendering the form. The initial value is only used in a unbound form, if it's bound and a value for that field is not included nothing will be selected.

Related