I
I
Irina Pakhomova2016-01-04 22:56:04
Django
Irina Pakhomova, 2016-01-04 22:56:04

How to write a middleware to display an extra line on each page?

I understand little by little with middleware. But I still can't figure it out.
Here is an example that does not work for me: python.su/forum/topic/11368
I also write process_response. The docs say that response is the HttpResponse. I check, for some reason I have a TemplateResponse. Is there something wrong with my views? Okay, I did it like this:
class MyOwnMiddleWare(object):
def process_response(self, request, response):
content = response.rendered_content
content = content.replace('</body>', ' my piece of text '</body >')
response = HttpResponse(content, content_type="text/html")
return response
And it works on some pages. But some do not :))) The error 'HttpResponseRedirect' object has no attribute 'rendered_content' occurs, that is, the response is already another object.
How can I fix this? Do I do this at all? And then there is still a process_template_response method, maybe it is needed?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
Oscar Django, 2016-01-05
@Vdomike

And then there is still a process_template_response method, maybe it is needed?

TemplateResponse inherits from SimpleTemplateResponse whose parent is HttpResponse. Therefore "response is the HttpResponse".
process_template_response is only executed if response has a render method, while process_response is always executed. You can see the logic process_template_response and process_response
The render method is set in the SimpleTemplateResponse class, from which, as we found out, TemplateResponse is inherited, but not HttpResponseRedirect.

U
un1t, 2016-01-04
@un1t

Check response.status_code - if it's 200 then change it, if it's different then don't change it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question