Django: set select choices dynamically in Forms

The Django Framework logo Sometimes we could need to set dynamically the choices of a select box in our forms. To do this we wish to pass as parameter the list of tuples to use in our form instance. To create this kind of form is easy. This is the code:

from django import forms

form = MyCustomForm(my_choices=list_of_tuples)

class MyCustomForm(forms.Form):
   def __init__(self, *args, **kwargs):
       choices = kwargs.pop('my_choices')
       super(MyCustomForm, self).__init__(*args, **kwargs)
       self.fields["my_field"] = forms.ChoiceField(choices=choices)
   
   other_field = forms.CharField()

References:

  1. Stackoverflow: Passing arguments to a dynamic form in Django
  2. Stackoverflow: Creating a dynamic choice field
Do you find this post useful? Please, consider to Flattr it.
blog comments powered by Disqus