Often times you’ll find that you need to use a constant that’s defined in your Django settings within a template. Unfortunately Django only provides access to a handful of settings by default. Anything beyond that small set, including custom constants that you have defined, are not accessible.
The easiest way to deal with this problem is to make use of a context processor. First, create a new file called context_processors.py within your application:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.conf import settings | |
def global_settings(request): | |
# return any necessary values | |
return { | |
'GOOGLE_ANALYTICS': settings.GOOGLE_ANALYTICS, | |
'GOOGLE_API_KEY': settings.GOOGLE_API_KEY | |
} |
In this example I am making two constants available within my templates – GOOGLE_ANALYTICS and GOOGLE_API_KEY.
Next, add this new context processor to your settings:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
TEMPLATE_CONTEXT_PROCESSORS = ( | |
… | |
'app.context_processors.global_settings', | |
) |
Now you can make use of the constant from within your template:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script type="text/javascript"> | |
var _gaq=[['_setAccount','{{ GOOGLE_ANALYTICS }}'],['_trackPageview']]; | |
</script> |
Hi, thx for help ! Easy solution workin !
Do you know how can I make my own title for each page ?
Thank you so much for this. Really great!
Thank you for sharing your knowledge š
Reblogged this on SYS HELL.
Thank you! Save my day!