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 开发者_如何学Pythondjango.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} )
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 }}
A simple context processor would do what you want
context_processors.py
import django
def django_version(request):
return { 'django_version': django.VERSION }
Dont forget to include this context processor in your settings under TEMPLATE_CONTEXT_PROCESSORS
You should provide the django.VERSION as variable to the template via the template context. I recommend following the django tutorial or read the django docs if you don't know how to do this.
You may want to use django.get_version()
to get the django version in string, the django.VERSION
returns a tuple.
>>> import django
>>> django.VERSION
(1, 11, 12, u'final', 0)
>>> django.get_version()
'1.11.12'
context_processors.py
import django
def django_version(request):
return {
'django_version': django.get_version() # django.VERSION (returns a tuple.)
}
Include this context processor in your project settings.py
file under TEMPLATE_CONTEXT_PROCESSORS
:
TEMPLATE_CONTEXT_PROCESSORS = (
#########
'myproject.context_processors.django_version',
)
精彩评论