Menu Close

How to create a dynamic choice field with Python Django?

To create a dynamic choice field with Python Django, we can set the fields to a queryset value.

For instance, we write

class WaypointForm(forms.Form):
    def __init__(self, user, *args, **kwargs):
        super(waypointForm, self).__init__(*args, **kwargs)
        self.fields['waypoints'] = forms.ChoiceField(
            choices=[(o.id, str(o)) for o in Waypoint.objects.filter(user=user)]
        )

to create the WaypointForm form.

In the __init__ method, we set self.fields['waypoints'] to a ChoiceField.

And we populate the choices by setting the choices argument to a list of values that we get from the Waypoint.objects.filter(user=user) queryset.

Posted in Python, Python Answers