2014-09-01

Show the Django project version in the login page

I would like to display my Django project version string in the login page. However my project uses the Django Authentication System, which provides a login view (django.contrib.auth.views.login) which in turn uses my template file. Since I do not have control over the login view, how can I pass the version string into the template?
Turn out that the login view is a generic view and all generic views take an extra optional parameter, extra_context, which is a dictionary of objects that will be added to the template's context.
All we have to do is to add the version string to extra_context. We can do that in the urls.py. The url() function takes an optional argument which is a dictionary of extra keyword arguments to pass to the view function.
=== urls.py ===

VERSION = "1.0"

urlpatterns = patterns('',
    ...
    url(r'^accounts/login/$', 'django.contrib.auth.views.login', {'extra_context': {'version':VERSION}}),
)

=== template.html ===

{% extends "base.html" %}
{% block title %}Project Name {{ version }}{% endblock %}
{% block content %}{% endblock %}

No comments: