Search code examples
pythondjangotemplatestags

Django template tag to display Django version


What is the simplest way to create a Django template tag which displays the Django version on a template?

I want to put the following in a Django template and have it output the Django version (in my case, base.html):

{{ django_version }}

I know that the following Python code outputs the Django version in a shell, but am confused about where I should put this code and how I should call it from the template:

import django
print django.VERSION

UPDATE: I have tried the following in views.py, but nothing shows up in the template:

import django    
from django.template import loader, Context
from django.http import HttpResponse
from django.shortcuts import render_to_response

    def base(request):
        django_version = django.VERSION
        return render_to_response('base.html', {'django_version': django_version} )

Solution

  • Figured this out (currently using Django 1.3) — I needed to append the function name 'django_version' to the TEMPLATE_CONTEXT_PROCESSORS tuple in settings.py:

    TEMPLATE_CONTEXT_PROCESSORS = (  
        # ...  
        'myproject.context_processors.django_version',  
    )
    

    context_processors.py (thanks to zsquare):

    import django
    def django_version(request):
        return { 'django_version': django.VERSION }
    

    urls.py:

    urlpatterns += patterns('django.views.generic.simple',
        (r'^$', 'direct_to_template', {'template': 'base.html'}),
    )
    

    Put the following in your templates, such as base.html:

    {{ django_version }}