Getting the template name in django template

The easy way:

Download and use the django debug toolbar. You'll get an approximation of what you're after and a bunch more.

The less easy way:

Replace Template.render with django.test.utils.instrumented_test_render, listen for the django.test.signals.template_rendered signal, and add the name of the template to the context. Note that TEMPLATE_DEBUG must be true in your settings file or there will be no origin from which to get the name.

if settings.DEBUG and settings.TEMPLATE_DEBUG

    from django.test.utils import instrumented_test_render
    from django.test.signals import template_rendered


    def add_template_name_to_context(self, sender, **kwargs)
        template = kwargs['template']
        if template.origin and template.origin.name
            kwargs['context']['template_name'] = template.origin.name

    Template.render = instrumented_test_render

    template_rendered.connect(add_template_name_to_context)

Templates are just strings not file names. Probably your best option is to monkey patch render_to_response and/or direct_to_template and copy the filename arg into the context.

Tags:

Python

Django