Home > Blockchain >  character "@" in the name of a variable in the django template
character "@" in the name of a variable in the django template

Time:12-01

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

CodePudding user response:

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.

Or for subdictionaries:

mydata_2 = {
    '1': {'@model': 'wolfen', '@genre': 'fantastic', 'price': '300'},
    '3': {'@model': 'phase4', '@genre': 'fantastic', 'price': '450'},
}
mydata_2 = {
    k: {ki[1:] if ki.startswith('@') else ki: v for ki, v in subdict.items()}
    for k, subdict in mydata_2.items()
}
  • Related