1. 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

    def javascript_url(request):
        from django.conf import settings
        return {'JAVASCRIPT_URL': settings.JAVASCRIPT_URL}

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

    from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS
    TEMPLATE_CONTEXT_PROCESSORS += (
         'django.core.context_processors.request',
         'django.core.context_processors.i18n',
         'appname.utils.context_processors.javascript_url',
    )

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

    {{ JAVASCRIPT_URL }}
    By timc3 on the
    January 22nd, 2010

Please post a comment