Default Selection in ChoiceField

10,739 views
Skip to first unread message

Sumanth

unread,
Feb 1, 2010, 7:56:26 PM2/1/10
to Django users
Hi all,

I have a basic form

class AssumptionsForm(forms.Form):
writedownoper = forms.ChoiceField( required=True, choices =
[('1','1'),('2',2='),('3','3')])

Now in my view after I create the form I want to set value 2 as
default. How can I do it? Is there set default API that I can use.

Thanks in advance
Sumanth

Rishabh Manocha

unread,
Feb 1, 2010, 10:26:45 PM2/1/10
to django...@googlegroups.com

There are two ways you can do this. If the initial choice for
'writedownoper' will always be '2', you can use pass an 'initial'
argument when declaring the field [1]:

writedownoper = forms.ChoiceField( required=True, choices =

[('1','1'),('2','2'),('3','3')], initial = '2')

However, if that value needs to be dynamic, you can do so when
instantiating the form in your view [2]:

writedownoper = forms.ChoiceField( required=True, choices =

[('1','1'),('2','2'),('3','3')])

views.py:

form = AssumptionsForm(initial = {'writedownopen' : '2'})


>
> Thanks in advance
> Sumanth
>
> --
> You received this message because you are subscribed to the Google Groups "Django users" group.
> To post to this group, send email to django...@googlegroups.com.
> To unsubscribe from this group, send email to django-users...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
>
>

--

Best,

R

[1] - http://docs.djangoproject.com/en/dev/ref/forms/fields/#initial
[2] - http://docs.djangoproject.com/en/dev/ref/forms/api/#dynamic-initial-values

Shawn Milochik

unread,
Feb 2, 2010, 2:09:30 AM2/2/10
to django...@googlegroups.com
You can do it in your view after creating the form, if you like.

form = SomeForm()
form.fields['meal_pref'].initial = 2

Shawn

Sumanth

unread,
Feb 2, 2010, 6:53:17 PM2/2/10
to Django users
Thanks guys
Both work

Sumanth

Reply all
Reply to author
Forward
0 new messages