Display field choice as part of model string name
13,371
Use get_gender_display()
:
return u"%s [%s]" % (self.name, self.get_gender_display())
Note, if you're not using Python 3+ you should be defining __unicode__
rather than __str__
.
Related videos on Youtube
Author by
Ed.
Updated on June 04, 2022Comments
-
Ed. almost 2 years
From the django documentation, what if I had
GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) class Person(models.Model): name = models.CharField(max_length=20) gender = models.CharField(max_length=1, choices=GENDER_CHOICES) def __str__(self): return "%s [%s]" % (self.name, self.gender)
What if I wanted the __str definition to display as the full name (Male or Female) for self.gender instead of M or F?
-
Ed. about 12 yearscan you explain the difference between unicode and str? And should I define them both?
-
jfunez about 11 yearsand in a template, you can use:
{{ variable.get_fieldname_display }}
HTH -
Torsten Engelbrecht over 7 yearsIn Python 3 you should be defining
__str__
rather than__unicode__
though.