Skip to content

Instantly share code, notes, and snippets.

@particledecay
Last active December 13, 2015 18:29
Show Gist options
  • Save particledecay/4955644 to your computer and use it in GitHub Desktop.
Save particledecay/4955644 to your computer and use it in GitHub Desktop.
[Django] Custom template filter to retrieve human-readable value from choices tuple or value from dict
from django import template
register = template.Library()
# Utility used like {{ dict|getval:key_name }} to return value even when using variables in dictionary key
@register.filter(name='getval')
def getval(tupdict, key_name):
"""Use this in a template as follows:
To retrieve the value of a dict:
{{ crime_rates_dict|getval:"Chicago" }} <-- will return value of crime_rates_dict["Chicago"]
To retrieve the human-readable value from a choices tuple:
{{ country.COUNTRIES|getval:"US" }} <-- will return "United States" in COUNTRIES = (("US", "United States"),)
"""
value = ''
if type(tupdict) == type(()):
# Assume this is likely a "choices" list, and the friendly value should be returned
try:
value = [choice[1] for choice in tupdict if key_name in choice]
value = value.pop()
except:
value = ''
elif type(tupdict) == type({}):
# This is a regular dictionary, and the requested value should be returned
value = tupdict.get(key_name, '')
return value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment