Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Set field choices from view?

I've got some <selects> that I need to populate with some choices that depend on the currently logged in user. I don't think this is possible (or easy) to do from inside the form class, so can I just leave the choices blank and set them in the view instead? Or what approach should I take?

like image 666
mpen Avatar asked Aug 12 '10 01:08

mpen


2 Answers

Not sure if this is the best answer, but in the past I have set the choices of a choice field in the init of the form - you could potentially pass your choices to the constructor of your form...

like image 160
Matthew J Morrison Avatar answered Oct 10 '22 20:10

Matthew J Morrison


You could build your form dynamically in you view (well, actually i would rather keep the code outside the view in it's own function and just call it in the view but that's just details)

I did it like this in one project:

user_choices = [(1, 'something'), (2, 'something_else')]
fields['choice'] = forms.ChoiceField(
    choices=user_choices,
    widget=forms.RadioSelect,
)
MyForm = type('SelectableForm', (forms.BaseForm,), { 'base_fields': fields })
form = MyForm()

Obviously, you will want to create the user_choices depending on current user and add whatever field you need along with the choices, but this is a basic principle, I'll leave the rest as the reader exercise.

like image 25
Davor Lucic Avatar answered Oct 10 '22 21:10

Davor Lucic