Why can't I hyphen in a Django template view?

{{profile.first-name.value}} 

My variable is just hypeh ... I would like to make first_name , but many variables are hyphens. However, due to this problem, I cannot display my variables in the template. Why?

+3
source share
2 answers

A hyphen is an operator in Python. This will work better if you replace all hyphens for underscores.

+8
source

OrderedDict dictionary types support hyphens: 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 
0
source

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


All Articles