9👍
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!
7👍
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 = .....)
- Place to set SQLite PRAGMA option in Django project
- Can't connect to server running inside docker container (Docker for mac)
- Override JSONSerializer on django rest framework
- Django ModelChoiceField: how to iter through the instances in the template?
- How to format django template in Sublime Text
3👍
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): …’
- Django datefield and timefield to python datetime
- Django QuerySet object has no attribute 'objects
- Systemctl strange error: Invalid arguments
Source:stackexchange.com