Reputation: 441
I am trying to figure out how to set the initial value of a ModelChoiceField when it's created (not on form creation). Below is a very simplified example of what I have now, and I'd like to set a default for State and Country when they render.
I thought this could be done in the SetBillingInfo
class in Forms.py
, but can't get it to work. Say I want to default to California for state and United States for country. Is there a way to set this?
FORMS.PY
class SetBillingInfo(forms.Form):
state = forms.ModelChoiceField(
queryset=States.objects.all().order_by('group_order','name'),
to_field_name='name',
label = '',
required=False
)
country = forms.ModelChoiceField(
queryset=Country.objects.all().order_by('group_order','name'),
to_field_name='name',
label = '',
required=True
)
VIEWS.PY
billinginfo = SetBillingInfo(initial=request.GET)
return render(request, 'index.html',{'billinginfo': billinginfo})
INDEX.HTML (this is not exactly correct but you get the idea)
{% for field in billinginfo %}
<select class="FormRow">
{{ field }}
</select>
{% endfor %}
Upvotes: 1
Views: 773
Reputation: 4616
in forms.py
default_state=States.objects.get(name='California')
state = forms.ModelChoiceField(
queryset=States.objects.all().order_by('group_order','name'),
to_field_name='name',
label = '',
initial=default_state,
required=False
)
Upvotes: 1