setting a pre-selected value for the ChoiceField

2,986 views
Skip to first unread message

Christopher Clarke

unread,
Jul 29, 2008, 12:14:23 PM7/29/08
to Django users
Hi guys
I'm using the third party django-profiles app.
I have a ChoiceField in my form/model of countries for the user.
This is the ISO country list in a model called Country
Most of the users are from Trinidad so i want to put this pre-
selected in the drop down like
<select name="test">
<option value="US">USAi</option>
<option value="TT" selected="selected">Trinidad</option>

</select>
I have tried
country=
forms
.ModelChoiceField
(required=True,queryset=Country.objects.filter(active=True),

empty_label
=None,initial=Country.objects.get(description__contains='Trinidad'))
but this does not seem to work

How do i do this
Thank for the help
Regards
Chris

Daniel

unread,
Aug 9, 2008, 1:37:23 AM8/9/08
to Django users
Ran into this myself just now.

I was using a ChoiceField, but I assume it will work the same for a
ModelChoiceField:

choice = forms.ChoiceField(choices = arr,
widget=forms.Select(attrs="12"))


When declaring the field, I declared the Select widget to be used with
it. I did this because I found in the Select code where it decides
whether to add the selected="Selected", but it took me forever to
figure out how to talk to the widget.

So I'd try in your case adding
widget=forms.Select(attrs="TT")

and seeing what happens.



Hope that helps.

Ugandhar Reddy

unread,
Oct 7, 2008, 1:02:27 PM10/7/08
to Django users
I had similar requirement i.e showing a pre-selected value in the
ChoiceField after looking into the ChoiceField django code its become
clear to me that the value of the text to be assigned to initial.

With this change country field in the Form object looks like:

country = forms.ChoiceField(required=True, choices=arr,
label="Country", initial="TT")

Considering "TT" is the value associated with "Trindbad" text in the
"arr" list of tuples.

This might help you or others who might face this.
Reply all
Reply to author
Forward
0 new messages