Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set choices in dynamic with Django choicefield?

Tags:

python

django

I want to set choices in dynamic.

I used __set_choices method but, when request method is POST, is_valid method always return False.

if request.method=='POST':
 _form = MyForm(request.POST)
 if _form.is_valid():
   #something to do
like image 448
rtv5t5t4 Avatar asked Feb 17 '11 12:02

rtv5t5t4


1 Answers

I often set the choices dynamicly in the constructor:

class MyForm(BaseForm):
    afield = forms.ChoiceField(choices=INITIAL_CHOICES)

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['afield'].choices = my_computed_choices
like image 173
maersu Avatar answered Oct 02 '22 20:10

maersu