[Django]-Django ModelChoiceField using distinct values from one model attribute

8👍

The second way will work, but you need to set the choices on init so its refreshed each time the form is called.

e.g

class QueryForm(forms.Form):
    hostname = forms.ChoiceField(choices=[], required=False)

    def __init__(self, *args, **kwargs):
        super(QueryForm, self).__init__(*args, **kwargs)
        self.fields['hostname'].choices = Event.objects.all().values_list("hostname","hostname").distinct()
👤JamesO

Leave a comment