Creating a dynamic choice field Creating a dynamic choice field python python

Creating a dynamic choice field


you can filter the waypoints by passing the user to the form init

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)]        )

from your view while initiating the form pass the user

form = waypointForm(user)

in case of model form

class waypointForm(forms.ModelForm):    def __init__(self, user, *args, **kwargs):        super(waypointForm, self).__init__(*args, **kwargs)        self.fields['waypoints'] = forms.ModelChoiceField(            queryset=Waypoint.objects.filter(user=user)        )    class Meta:        model = Waypoint


There's built-in solution for your problem: ModelChoiceField.

Generally, it's always worth trying to use ModelForm when you need to create/change database objects. Works in 95% of the cases and it's much cleaner than creating your own implementation.


the problem is when you do

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)])

in a update request, the previous value will lost!