Sometimes, we want to show the verbose version of a choice with Python Django templates.
In this article, we’ll look at how to show the verbose version of a choice with Python Django templates.
How to show the verbose version of a choice with Python Django templates?
To show the verbose version of a choice with Python Django templates, we can create a model class with our own method to return the verbose version of the choice.
For instance, we write
from django.db import models
class Scoop(models.Model):
FLAVOR_CHOICES = [
('c', 'Chocolate'),
('v', 'Vanilla'),
]
flavor = models.CharField(choices=FLAVOR_CHOICES)
def flavor_verbose(self):
return dict(Scoop.FLAVOR_CHOCIES)[self.flavor]
to create the flavor_verbose
method.
In it, we convert FLAVOR_CHOICES
to a dict with dict(Scoop.FLAVOR_CHOCIES)
.
And then we get the verbose version of the choice with self.flavor
.
Then in our template, we write
{{ scoop.flavor_verbose }}
to show the choice.
Conclusion
To show the verbose version of a choice with Python Django templates, we can create a model class with our own method to return the verbose version of the choice.