views:

3326

answers:

6

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.

A few results I've found through Google suggest it is possible to set the initial value but I've never ever managed to get it to work! I am on django 1.0 by the way.

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

Many thanks.

A: 

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.

Andrew Wilkinson
A: 

Your code snippet is fine. As Andrew said, how are you rendering the form? And how is the form instance instantiated in your view before being passed to the template?

bryan
+4  A: 

Try setting the initial value when you instantiate the form:

form = MyForm(initial={'max_number': '3'})
Tom
works fine for me
dasha salo
+3  A: 

I ran into this problem as well, and figured out that the problem is in the browser. When you refresh the browser is re-populating the form with the same values as before, ignoring the checked field. If you view source, you'll see the checked value is correct. Or put your cursor in your browser's URL field and hit enter. That will re-load the form from scratch.

Dave
A: 

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
Michael
+3  A: 

You can also do the following. in your form class def:

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

then when calling the form in your view you can dynamically set both initial choices and choice list.

yourFormInstance = YourFormClass()

yourFormInstance.fields['max_number'].choices = [(1,1),(2,2),(3,3)]
yourFormInstance.fields['max_number'].initial = [1]

Note: the initial values has to be a list and the choices has to be 2-tuples, in my example above i have a list of 2-tuples. Hope this helps.

Cheers,

Burton Williams