Django: set select choices dynamically in Forms
January 27, 2013Last update: March 29, 2020
The problem
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.
A solution
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
-
Passing arguments to a dynamic form in Django on Stack Overflow
-
Creating a dynamic choice field on Stack Overflow