Reputation: 492
I have a Django model in which I'm using the choices parameter. For the choices, I'm using a Python Enum. Now I want to display the choices display value in a template. I know there's .get_fieldname_display
but it just returns the key instead of the display value in this case.
Model:
class LocalTitle(models.Model):
type = models.CharField(max_length=8, choices=[(tag, tag.value) for tag in LocalTitleCodes])
title = models.CharField(max_length=255)
Enum:
class LocalTitleCodes(Enum):
title_00 = 'Japanese'
title_01 = 'English'
title_02 = 'French'
So in my case, if I do title.get_type_display
in my template it returns title_00
and not Japanese
. How can I get the display value?
Upvotes: 4
Views: 7059
Reputation: 477180
I think the problem is more that tag
does not map to title__00
, but to a LocalTitleCodes
object.
You should use:
class LocalTitle(models.Model):
type = models.CharField(
max_length=8,
choices=[(tag.name, tag.value) for tag in LocalTitleCodes]
)
title = models.CharField(max_length=255)
Since Django thus could not find a the corresponding value, it fallsback on the value stored in the database.
Since:
>>> [(tag, tag.value) for tag in LocalTitleCodes]
[(<LocalTitleCodes.title_00: 'Japanese'>, 'Japanese'), (<LocalTitleCodes.title_01: 'English'>, 'English'), (<LocalTitleCodes.title_02: 'French'>, 'French')]
>>> [(tag.name, tag.value) for tag in LocalTitleCodes]
[('title_00', 'Japanese'), ('title_01', 'English'), ('title_02', 'French')]
Upvotes: 4
Reputation: 1608
class LocalTitle(models.Model):
LOCALCODES = (
('title_00' , 'Japanese')
('title_01' ,'English')
('title_02' , 'French')
)
type = models.CharField(max_length=8, choices=LOCALCODES)
title = models.CharField(max_length=255)
Or you can give your choice like this.
Upvotes: 3