Django Form ChoiceField, initial not working

1,287 views
Skip to first unread message

Sector7B

unread,
Dec 9, 2010, 5:18:10 PM12/9/10
to Django users
Hi, i have a simple form:
class StoreLocationHoursForm(BForm):
location = forms.ChoiceField(required=True)
day = forms.ChoiceField(choices=bagit_constants.dow,required=True)
time_open_hours =
forms.ChoiceField(choices=constants.hours,required=True)
time_open_minutes =
forms.ChoiceField(choices=constants.minutes,required=True)
time_close_hours =
forms.ChoiceField(choices=constants.hours,required=True)
time_close_minutes =
forms.ChoiceField(choices=constants.minutes,required=True)

there can be many locations, so in my view i loop through them to
create a list of tuples to provide a choices list for location:
Log Output of the list when im done:sl_list= [('-', 'Choose
Location'), (u'Super City', u'901 PHILADELPHIA STREET')]

the code i use to set initial is the following:

form = StoreLocationHoursForm(initial={"location":sl_list})

However my select is empty when it renders the HTML.

Thanks for the help in advance,

j

Sævar Öfjörð

unread,
Dec 11, 2010, 6:08:06 AM12/11/10
to Django users
I think you should provide your choices in the form field, not when
creating an instance of the form.
The form would then be something like this:

class StoreLocationHoursForm(BForm):
sl_list= [('-', 'Choose Location'), (u'Super City', u'901
PHILADELPHIA STREET')]
location = forms.ChoiceField(choices=sl_list, required=True)
# rest of fields...

The initial keyword when creating an instance of the form is used to
select which of the choices is rendered as selected.
Haven't tested this though.

- Sævar

wayne

unread,
Dec 11, 2010, 12:29:43 PM12/11/10
to Django users

On Dec 11, 5:08 am, Sævar Öfjörð <saeva...@gmail.com> wrote:
> I think you should provide your choices in the form field, not when
> creating an instance of the form.

Agreed. To create a dynamic form such as this, the best way would
probably be to use a custom __init__ function. In your view, when you
create your form, you can pass in a 'queryset=' argument that will do
this for you.

Wayne
Reply all
Reply to author
Forward
0 new messages