Django settings.py variables in templates

mythander889 picture mythander889 · Aug 28, 2012 · Viewed 7.5k times · Source

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",
)

Answer

Simeon Visser picture Simeon Visser · Aug 28, 2012

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.