SteveV
SteveV

Reputation: 441

Set initial value in ModelChoiceField at setup

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

Answers (1)

Abhijith Konnayil
Abhijith Konnayil

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

Related Questions