Django settings.py variables in templates

a 夏天 提交于 2019-11-30 04:47:52

问题


I'm encountering a very strange error. I have an app ID defined in my settings.py file like so:

CARDSPRING_APP_ID = '################'

This works on nearly every page in my site, except for one. Strangely enough, other variables work. In a script section on the page, I have the following:

alert("cs appid=" + {{ CARDSPRING_APP_ID }} + 
" sectoken=" + {{ securityToken }} + 
" timestamp= " +{{ timestamp }} + 
" hash = " + {{ digestedHash }} + 
" ccnum " + $('.card-number').val() + 
" exp" + $('.expiration-month').val() + $('.expiration-year').val() + 
" user = " + {{ csid }});

When the page is rendered, it evaluates to this

alert("cs appid=" +  + 
" sectoken=" + DDFJRMZXD12WVWHFFC###### + 
" timestamp= " +1346183125 + 
" hash = " + a929b3aec9179c700c09d###### + 
" ccnum " + $('.card-number').val() + 
" exp" + $('.expiration-month').val() + $('.expiration-year').val() + 
" user = " + SG1###);

Importantly, {{ CARDSPRING_APP_ID }} has evaluated to nothing. Does anyone know why this might be the case? Thank you!

UPDATE

I tried creating a context_processors.py file as described in the answer below, and made sure to add it to the appropriate spot in settings.py . I still don't have any luck -- it evaluates on one page, but not on the other

UPDATE 2

The template is called with this command:

return render_to_response('howto'+str(number)+'.html',locals(),context_instance= RequestContext(request))

UPDATE 3 Got it to work -- needed to add this to my settings.py

TEMPLATE_CONTEXT_PROCESSORS = global_settings.TEMPLATE_CONTEXT_PROCESSORS + (
    "myapp.context_processors.cardspring",
)

回答1:


Create a file called context_processors.py and write the following context processor:

from django.conf import settings

def cardspring(request):
    return { 'CARDSPRING_APP_ID': settings.CARDSPRING_APP_ID }

Then add your.location.context_processors.cardspring to TEMPLATE_CONTEXT_PROCESSORS in your Django settings file, where your.location is the location of your context_processors.py file.



来源:https://stackoverflow.com/questions/12166537/django-settings-py-variables-in-templates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!