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?
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:
Which you use like so:
If you want to access an object’s attribute with an arbitrary string name, you could use the following:
Which you would use like:
You could even come up with some sort of string seperator (like ‘__’) for subattributes, but I’ll leave that for homework 🙂