Categories
Python Answers

How to create a dynamic choice field with Python Django?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *