Django settings in template

         ·

So what do you do if you require a django setting in your templates, much like we have MEDIA_URL today?

Well there are use cases for this, (if you are in doubt have a look at the original ticket for adding MEDIA_URL to django ).

The easiest way that I have found so far is to write a context processor. For example in my settings I might have JAVASCRIPT_URL (which in my real life code changes depending on whether I am running in debug, test or from a CDN):

JAVASCRIPT_URL = 'http://myjshost.com'

Now from here I would like to make this available in my templates. Create a new python file that is somewhere on your python path (Under my project, I create a utils directory and then put a file context_processors.py in there. Don’t forget \__init__.py should live in that directory as well).

In the context_processors.py file simply put

<br /> def javascript_url(request):<br /> from django.conf import settings<br /> return {‘JAVASCRIPT_URL’: settings.JAVASCRIPT_URL}<br />

In your settings.py file you might already have a reference to TEMPLATE_CONTEXT_PROCESSORS if not then add it like so:

<br /> from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS<br /> TEMPLATE_CONTEXT_PROCESSORS += (<br /> ‘django.core.context_processors.request’,<br /> ‘django.core.context_processors.i18n’,<br /> ‘appname.utils.context_processors.javascript_url’,<br /> )<br />

And thats about it. From there on in you will be able to use JAVASCRIPT_URL like MEDIA_URL:

{{ JAVASCRIPT_URL }}

comments powered by Disqus