Saturnix
Saturnix

Reputation: 10564

process_template_response doesn't get called in Django

In views.py I use render() .

In app -> middleware.py I have this code:

from django.conf import settings


class NoTrackingMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        return response

    def process_template_response(self, request, response):
        no_tracking = True if request.GET.get("NO_TRACKING", default=False) is not False else False
        pub_id = "PUBLISHER_TEST" if no_tracking is True else settings.WFF_PUB_ID
        response.context_data["no_tracking"] = no_tracking
        response.context_data["pub_id"] = pub_id
        return response

In settings.py I have:

MIDDLEWARE = [
...
    'app.middleware.NoTrackingMiddleware',
]

Yet if I place a breakpoint at process_template_response it gets ignored and pub_id is always empty.

Why?

Upvotes: 3

Views: 425

Answers (1)

solarissmoke
solarissmoke

Reputation: 31404

From the documentation (emphasis mine):

process_template_response() is called just after the view has finished executing, if the response instance has a render() method, indicating that it is a TemplateResponse or equivalent.

You state that you're using django.http.shortcuts.render, whose documentation reads:

Combines a given template with a given context dictionary and returns an HttpResponse object with that rendered text.

Django does not provide a shortcut function which returns a TemplateResponse because the constructor of TemplateResponse offers the same level of convenience as render().

Thus render returns a HttpResponse, not a TemplateResponse, and as noted above, process_template_response is only called for TemplateResponses.

You either need to change your view to return TemplateResponse, instead of using the render shortcut, or perform your logic elsewhere. I think your logic could be implemented in a context processor instead of middleware.

Upvotes: 6

Related Questions