Setting the selected value on a Django forms.ChoiceField
Try setting the initial value when you instantiate the form:
form = MyForm(initial={'max_number': '3'})
This doesn't touch on the immediate question at hand, but this Q/A comes up for searches related to trying to assign the selected value to a ChoiceField
.
If you have already called super().__init__
in your Form class, you should update the form.initial
dictionary, not the field.initial
property. If you study form.initial
(e.g. print self.initial
after the call to super().__init__
), it will contain values for all the fields. Having a value of None
in that dict will override the field.initial
value.
e.g.
class MyForm(forms.Form):
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
# assign a (computed, I assume) default value to the choice field
self.initial['choices_field_name'] = 'default value'
# you should NOT do this:
self.fields['choices_field_name'].initial = 'default value'