[Answered ]-Django – Need to access the current template name in middleware

2👍

You might want to use django-debug-toolbar and it’s template panel instead of reinventing the wheel.

FYI, as you can see, it gets template name by monkey-patching django Template class. The code is based on this snippet.

Hope that helps.

👤alecxe

0👍

If your view is class based you can do:

from contextlib import suppress

class MyMiddleware(SessionMiddleware):
    def process_response(self, request, response):
        html = response.content
        dostuff()
        return super().process_response(request, response)

    def process_view(self, request, view_func, view_args, view_kwargs):
        with suppress(AttributeError):
            template_name = view_func.view_class.template_name
        with suppress(AttributeError):
            # Do something else for function based views, e.g. add it as an attribute to the function
            return view_func.template_name
        print(template_name)
        return None

Leave a comment