[Solved]-Django forms: how to dynamically create ModelChoiceField labels


You could use a ModelChoiceField and then change the choices in you ProfileForm.__init__ dynamically, eg (assuming that it is already a ModelChoiceField):

horoscopes = Horoscope.objects.all()
self.fields['horoscope'].choices = [(h.pk, h.name) for h in horoscopes]

h.name in this example will be used as the label of the choice!


You can make your own form field class and overwrite the method that generates the label:

class MyChoiceField(ModelChoiceField):
   def label_from_instance(self, obj):
        # return your own label here...
        return smart_unicode(obj)

use it in your form same as you did with the ModelChoiceField:

horoscope = MyChoiceField(queryset = .....)


Actually the last code example contains errors an should be:

# this function is added
def get_label(obj):
    return '%s: Euro %.2f' % (HoroscopeLanguage.objects.get(horoscope=obj, language__language_code=language_code).horoscope_type_language, obj.price)

self.fields['horoscope'].label_from_instance = get_labels

Then it works. There is no difference in using ‘lambda obj:…’ or ‘def get_label(obj): …’


Leave a comment