[Answer]-Django adding an empty label to Choice Field using a ValueListQuery Set for distinct values

1👍

This is because the super(FilterForm, self).__init__(*args, **kwargs) will call the EmptyChoiceField.__init__ method, and you are then overriding the choices right after the super call so you are overridding the choices the EmptyChoiceField set.

There are a few ways to solve this, I am not sure which one is the best, but the easiest way is to do the following in the FilterForm.__init__:

def __init__(self, *args, **kwargs):
    super(FilterForm, self).__init__(*args, **kwargs)
    choices = Stuff.objects.all().values_list("y", "y").distinct()
    self.fields['y'].choices = tuple([(u'', empty_label)] + list(choices))
👤vishen

Leave a comment