We have a system built on a custom database, where many of the attributes are named containing hyphens, ie:
user-name
phone-number
These properties cannot be accessed in templates as follows:
{{ user-name }}
Django throws an exception for this. I'd like to avoid having to convert all of the keys (and sub-table keys) to use underscores just to work around this. Is there an easier way?
Accessing Elements from Dictionary Keys can be used either inside square brackets [] or with the get() method. If we use the square brackets [] , KeyError is raised in case a key is not found in the dictionary. On the other hand, the get() method returns None if the key is not found.
The methods dict. keys() and dict. values() return lists of the keys or values explicitly. There's also an items() which returns a list of (key, value) tuples, which is the most efficient way to examine all the key value data in the dictionary.
Some of the ways you can check if a given key already exists in a dictionary in Python are using: has_key() if-in statement/in Operator. get()
It is flexible in that it allows a dictionary to contain keys of a wide variety of types. For example, the same dictionary can contain keys that are integers, floats, tuples, booleans, strings, and other types. But, due to this diversity of types of keys, dictionaries are considered to be unordered.
Unfortunately, I think you may be out of luck. From the docs:
Variable names must consist of any letter (A-Z), any digit (0-9), an underscore or a dot.
A custom template tag is probably the only way to go here if you don't want to restructure your objects. For accessing dictionaries with an arbitrary string key, the answer to this question provides a good example.
For the lazy:
from django import template
register = template.Library()
@register.simple_tag
def dictKeyLookup(the_dict, key):
# Try to fetch from the dict, and if it's not found return an empty string.
return the_dict.get(key, '')
Which you use like so:
{% dictKeyLookup your_dict_passed_into_context "phone-number" %}
If you want to access an object's attribute with an arbitrary string name, you could use the following:
from django import template
register = template.Library()
@register.simple_tag
def attributeLookup(the_object, attribute_name):
# Try to fetch from the object, and if it's not found return None.
return getattr(the_object, attribute_name, None)
Which you would use like:
{% attributeLookup your_object_passed_into_context "phone-number" %}
You could even come up with some sort of string seperator (like '__') for subattributes, but I'll leave that for homework :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With