Django: set select choices dynamically in Forms

January 27, 2013

Last 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

  1. Passing arguments to a dynamic form in Django on Stack Overflow

  2. Creating a dynamic choice field on Stack Overflow


A photo of Elia Contini
Written by
Elia Contini
Sardinian UX engineer and a Front-end web architect based in Ticino, Switzerland. Marathoner, traveller, wannabe nature photographer.