Login

Retrieve human-readable value from choices tuple or value from dict

Author:
JoeLinux
Posted:
February 7, 2013
Language:
Python
Version:
1.4
Score:
0 (after 0 ratings)

Will help you retrieve the value from a dictionary with a supplied key, or the human-readable value from a choices tuple. Works 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"),)`
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.