Django: How can I identify the calling view from a template?

No, and it would be a bad idea. To directly refer to a view function name from the template introduces overly tight coupling between the view layer and the template layer.

A much better solution here is Django's template inheritance system. Define a common parent template, with a block for the (small) area that needs to change in each view's version. Then define each view's template to extend from the parent and define that block appropriately.


Since Django 1.5, the url_name is accessible using:

request.resolver_match.url_name

Before that, you can use a Middleware for that :

from django.core.urlresolvers import resolve

class ViewNameMiddleware(object):  
    def process_view(self, request, view_func, view_args, view_kwargs):
        url_name = resolve(request.path).url_name
        request.url_name = url_name

Then adding this in MIDDLEWARE_CLASSES, and in templates I have this:

{% if request.url_name == "url_name" %} ... {% endif %}

considering a RequestContext(request) is always passed to the render function. I prefer using url_name for urls, but one can use resolve().app_name and resolve().func.name, but this doesn't work with decorators - the decorator function name is returned instead.

Tags:

Django