Access Django Constants from settings.py in a Template

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:

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:

TEMPLATE_CONTEXT_PROCESSORS = (
'app.context_processors.global_settings',
)

view raw
settings.py
hosted with ❤ by GitHub

Now you can make use of the constant from within your template:

<script type="text/javascript">
var _gaq=[['_setAccount','{{ GOOGLE_ANALYTICS }}'],['_trackPageview']];
</script>

view raw
template.html
hosted with ❤ by GitHub

5 thoughts on “Access Django Constants from settings.py in a Template”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s