Jun 16 2013

Django: Displaying ChoiceField Value in templates

in blog How to be a Ninja 101
original entryDjango: Displaying ChoiceField Value in templates

choicefield django django templates how to templates values

Hello, this note shows how to display the values you set for your ChoiceField in your templates. Some people (including me before Lol).. creates custom template tags just to show these values. It’s kinda annoying right? XD

Here’s the proper and simplier way to print those: ( example )

Source Code:

Models.py:
class AwesomePeople(models.Model):
    """List of awesome people"""
    LEVEL = (
        ('c', 'Cool Guy'),
        ('g', 'Genius'),
        ('h', 'Hardworking'),
        ('b', 'Beast'),
        ('n', 'Ninja'),
    )
    name = models.CharField(max_length=255)
    level = models.CharField(max_length=1, choices=LEVEL)
template.html

{% for person in awesome_list %}
    {{ person.name }}
    {{ person.get_level_display }}
{% endfor %}
    

just follow this format .get_<choicefield_name>_display

That’s it! I hope it helps. ;)



Tag cloud


Social Sharing

Feeds