character "@" in the name of a variable in the django template

Question:

I have a dictionary in my views.py

mydata = {'@model': 'wolfen', '@genre': 'fantastic', 'price: '350'}

which I pass to the django view in a context like this

context['mydata'] = mydata

and in my view i display like this

{{mydata.@model}}

the problem is that the django template uses the "@" character for other tags.
How to replace the "@" character to not display the following error

Could not parse the remainder: '@model' from 'mydata.@model'

thank you

the solution of Willem work fine.

I have another nested dictionary that looks different

mydata_2 ={'1' {'@model': 'wolfen', '@genre': 'fantastic', 'price': '300'} , {'3' {'@model': 'phase4', '@genre': 'fantastic', 'price': '450'} }

the keys of the main dictionaries ("1" , "3") can change dynamically.

otherwise a big thank you to Willem

Asked By: Zembla

||

Answers:

Rename the data, for example with:

mydata = {'@model': 'wolfen', '@genre': 'fantastic', 'price': '350'}
mydata = {k[1:] if k.startswith('@') else k: v for k, v in mydata.items()}
context['mydata'] = mydata

Then you can use {{ mydata.model }} in the template.

Answered By: Willem Van Onsem
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.