[Django]-Setting the selected value on a Django forms.ChoiceField

136👍

Try setting the initial value when you instantiate the form:

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

119👍

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'

69👍

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.

22👍

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

11👍

Both Tom and Burton’s answers work for me eventually, but I had a little trouble figuring out how to apply them to a ModelChoiceField.

The only trick to it is that the choices are stored as tuples of (<model's ID>, <model's unicode repr>), so if you want to set the initial model selection, you pass the model’s ID as the initial value, not the object itself or it’s name or anything else. Then it’s as simple as:

form = EmployeeForm(initial={'manager': manager_employee_id})

Alternatively the initial argument can be ignored in place of an extra line with:

form.fields['manager'].initial = manager_employee_id
👤orlade

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

2👍

Note: This answer is quite comprehensive and focuses on both static and dynamic initial values as this Q/A comes up for searches related to dynamic changing of initial value, and I believe that the information below will be of great use to junior programmers.

How to set the initial value

There are multiple options how to set the initial value of a ChoiceField (or any other field, e.g. DecimalField). The various options can be

  • static (i.e. initial value doesn’t change),
  • form-dynamic (i.e. initial value can be calculated/changed in the form constructor in forms.py),
  • view-dynamic (i.e. initial value can be calculated/changed in the view.py).

All of the options presented below can be combined, but beware of the initial value precedences!

Option A – Static initial value defined in the class

You can set the initial value right in the definition of the field in the form class. This option is only static.

In forms.py:

class MyForm(forms.Form):
     max_number = forms.ChoiceField(initial='3')

Option B – Initial value defined in instance constructor

You can set the initial value when creating a form instance. This option can be static or form-dynamic.

In forms.py:

class MyForm(forms.Form):
    max_number = forms.ChoiceField()
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.initial['max_number'] = '3'

You could also use self.fields['max_number'].initial = '3' instead of self.initial['max_number'] = '3' but this is not recommened unless you want the initial value to be overridable.

Option C – Initial value in the form call

You can set the initial value in the arguments of the form call. This option can be static or view-dynamic.

In views.py:

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

Option D – Initial value using keyword arguments

You can also send the initial value as a keyword argument (kwarg) to the form constructor, and then use this kwarg as the initial value. This option can be static, form-dynamic or view-dynamic.

In views.py:

my_form = MyForm(my_init_kwarg=3)

In forms.py:

class MyForm(forms.Form):
    max_number = forms.ChoiceField()
    def __init__(self, *args, **kwargs):
        if 'my_init_kwarg' in kwargs:
            init_val = kwargs.pop('my_init_kwarg')
        else:
            init_val = 1  # fallback value if kwarg is not provided
        super().__init__(*args, **kwargs)
        self.initial['max_number'] = init_val

Note: Lines 4 to 7 can be simplified to init_val = kwargs.pop('my_init_kwarg', 1)

Option E – Create bound form

You can create the form as a bound form and pass the initial value as the data for the bound form. This option can be static or view-dynamic.

In views.py:

form_data = {'max_number':3}
my_form = MyForm(form_data)

In forms.py:

class MyForm(forms.Form):
    max_number = forms.ChoiceField()

For more about bound and unbound forms see Django docs.

Additional notes specific for ChoiceFields

Note that the initial value refers to the key of the item to be selected, not its index nor display text – see this answer. So, if you had this list of choices

choices = ([('3','three'), ('2','two'), ('1','one')]) 

and wanted to set one as the initial value, you would use

max_number = forms.ChoiceField(initial='1')

1👍

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.

Leave a comment