How to set a selection in dynamics using a Django select box?

I want to set options in dynamic mode.

I used the __set_choices method, but when the POST request method, the is_valid method always returns False.

  if request.method == 'POST':
  _form = MyForm (request.POST)
  if _form.is_valid ():
    #something to do
+7
source share
4 answers

I often set options dynamically 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 
+15
source

The key is to understand that choices can be any iterable:

 import uuid from itertools import count class MyForm(BaseForm): counter = count(1) @staticmethod def my_choices(): yield (uuid.uuid1, next(counter)) afield = forms.ChoiceField(choices=my_choices) 

Or any logic you like inside my_choices .

+3
source

In the view, you can do the following

- views.py

 lstChoices = _getMyChoices() form.fields['myChoiceField'].choices = lstChoices 

where lstChoices is a list of dynamically generated tuples for your options.

+1
source

Similar to maersu's solution, but if you have a ModelForm with a model that has a ForeignKey for another model, you might want to assign a field query, not a selection.

0
source