695👍
It looks like you were on the right track – get_FOO_display()
is most certainly what you want:
In templates, you don’t include ()
in the name of a method. Do the following:
{{ person.get_gender_display }}
51👍
For every field that has choices set, the object will have a get_FOO_display() method, where FOO is the name of the field. This method returns the “human-readable” value of the field.
In Views
person = Person.objects.filter(to_be_listed=True)
context['gender'] = person.get_gender_display()
In Template
{{ person.get_gender_display }}
- [Django]-Django Admin app or roll my own?
- [Django]-Is there a list of Pytz Timezones?
- [Django]-Troubleshooting Site Slowness on a Nginx + Gunicorn + Django Stack
0👍
I do this by defining constants the following way:
class Person(models.Model):
MALE = 'M'
FEMALE = 'F'
CATEGORY_CHOICES = (
(MALE, 'Male'),
(FEMALE, 'Female'),
)
name = models.CharField(max_length=200)
gender = models.CharField(max_length=200, choices=CATEGORY_CHOICES)
to_be_listed = models.BooleanField(default=True)
description = models.CharField(max_length=20000, blank=True)
The M and F values will be stored in the database, while the Male and Female values will display everywhere.
- [Django]-Python Socket.IO client for sending broadcast messages to TornadIO2 server
- [Django]-How to pass multiple values for a single URL parameter?
- [Django]-Do django db_index migrations run concurrently?
-2👍
Others have pointed out that a get_FOO_display method is what you need.
I’m using this:
def get_type(self):
return [i[1] for i in Item._meta.get_field('type').choices if i[0] == self.type][0]
which iterates over all of the choices that a particular item has until it finds the one that matches the items type
- [Django]-How to test Django's UpdateView?
- [Django]-Create a field whose value is a calculation of other fields' values
- [Django]-How do I install psycopg2 for Python 3.x?
Source:stackexchange.com