How to get dictionary keys containing hyphens from a Django template?

We have a system built on a user database, where many attributes have names containing hyphens, that is:

user-name phone-number 

These properties cannot be accessed in templates as follows:

 {{ user-name }} 

Django throws an exception for this. I would like you to not have to convert all the keys (and subcategory keys) to use underscores to get around this. Is there an easier way?

+6
source share
3 answers

A custom template tag is probably the only way to go here if you don't want to restructure your objects. A good example for accessing dictionaries with an arbitrary string key is the answer to this question .

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 not found return an empty string. return the_dict.get(key, '') 

What do you use like this:

 {% dictKeyLookup your_dict_passed_into_context "phone-number" %} 

If you want to access the attribute of an object with an arbitrary string name, you can 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 not found return None. return getattr(the_object, attribute_name, None) 

What would you like to use:

 {% attributeLookup your_object_passed_into_context "phone-number" %} 

You can even come up with some kind of string delimiter (like "__") for sub-attributes, but I will leave this for homework :-)

+8
source

Unfortunately, I think you might be out of luck. From docs :

Variable names must consist of any letter (AZ), any digit (0-9), underscore, or period.

+3
source

OrderedDict dictionary types support dash: https://docs.python.org/2/library/collections.html#ordereddict-objects

This seems to be a side effect of the implementation of OrderedDict. Note that key value pairs are actually passed as sets. I would argue that the OrderedDict implementation does not use the "key" passed in the set as the true dict key, thereby circumventing this problem.

Since this is a side effect of the implementation of OrderedDict, this may not be what you want to rely on. But it works.

 from collections import OrderedDict my_dict = OrderedDict([ ('has-dash', 'has dash value'), ('no dash', 'no dash value') ]) print( 'has-dash: ' + my_dict['has-dash'] ) print( 'no dash: ' + my_dict['no dash'] ) 

Result:

 has-dash: has dash value no dash: no dash value 
+1
source

Source: https://habr.com/ru/post/902275/


All Articles