Last update: March 29, 2020
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.
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()