[Django]-Django ModelChoiceField drop down box custom population

3👍

You can override the label_from_instance on the ModelChoiceField after it’s constructed.

self.fields['name'] = forms.ModelChoiceField(queryset = Options.objects.filter(option_type = s), label = field_label, required=False)
self.fields['name'].label_from_instance = lambda obj: "{0} {1}".format(obj.name, obj.color)

Update based on comment to only show the color once:

class MyModelChoiceField(forms.ModelChoiceField):
     def __init__(self, *args, **kwargs):
          super(MyModelChoiceField, self).__init__(self, *args, **kwargs)
          self.shown_colors = []


     def label_from_instance(self, obj):
          if obj.color not in self.shown_colors:
               self.shown_colors.append(obj.color)
               return "{0} {1}".format(obj.name, obj.color)
          else:
               return obj.name


self.fields['name'] = MyModelChoiceField(queryset = Options.objects.filter(option_type = s), label = field_label, required=False)

Leave a comment