Reputation: 1889
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
Upvotes: 128
Views: 200254
Reputation: 1485
If you want to set the default value directly on the choices
attribute, then this solution is a work around:
self.fields["category"].choices = [
("", "--------"),
*[(cat.id, cat.name) for cat in Cat.objects.all()]
]
If you have many select fields that need defaulting you can move this to a function:
from typing import List, Tuple, Type
from django.db import models
def set_choices(
*,
model: Type[models.Model],
key: str,
value: str,
default: str = "----select----",
) -> List[Tuple]:
choices = [("", default), *[
(getattr(m, key), getattr(m, value)) for m in model.objects.all()
]]
return choices
And use it like this:
self.fields["category"].choices = set_choices(model=Cat, key="id", value="name")
Upvotes: 0
Reputation: 421
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.
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
forms.py
),view.py
).All of the options presented below can be combined, but beware of the initial value precedences!
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')
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.
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'})
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)
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.
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')
Upvotes: 3
Reputation: 691
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.
Upvotes: 69
Reputation: 3659
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'
Upvotes: 121
Reputation: 2090
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
Upvotes: 11
Reputation:
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
Upvotes: 3
Reputation: 3261
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.
Upvotes: 22
Reputation: 44633
Try setting the initial value when you instantiate the form:
form = MyForm(initial={'max_number': '3'})
Upvotes: 142
Reputation: 10846
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.
Upvotes: 1