I'm trying to write a django middleware using process_template_response but I seems like it's not working, can anybody help me with this or maybe give an example on how to use the method.
below is my code:
class MiddleWare(object):
def process_template_reponse(self, request, response):
response.context_data = dict(title='title')
response.template_name = 'pages/helloworld.html'
return response
in settings.py
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.co开发者_如何学Gontrib.messages.middleware.MessageMiddleware',
'proj.app.middleware.MiddleWare', # here my middleware
)
in template
<!-- nothing is showing -->
{% block title %}{{ title }}{% endblock %}
by the way I'm using Django 1.3 rc 1
Thanks
http://docs.djangoproject.com/en/dev/topics/http/middleware/#process-template-response
Are you using the new SimpleTemplateResponse
response classes?
Your view must return SimpleTemplateResponse
or subclass for the new process_template_response
middleware hook to work.
Copied from the docs:
def my_view(request):
# Create a response
response = TemplateResponse(request, 'mytemplate.html', {})
# Register the callback
response.add_post_render_callback(my_render_callback)
# Return the response
return response
TL;DR: You must render your templates with TemplateResponse
:
from django.template.response import TemplateResponse
def myView(request):
context = {'foo':'foo_value'}
return TemplateResponse(request,'foo.html', context)
The problem arises when you render your templates with the good old render
imported from django.shorcuts
. As stated in the documentation for process_template_response()
, this hook gets called when the response is a TemplateResponse
or equivalent. So what you should do is to use TemplateResponse
to render your templates and your middleware will work.
You can also alias TemplateResponse
as render
so you don't have to change all your views. I personally don't recommend this.
from django.template.response import TemplateResponse as render
Here is a working example of a simple middleware that uses the process_template_response method.
class ExampleMiddleware(object):
def process_template_response(self, request, response):
response.context_data['title'] = 'We changed the title'
return response
This middleware changes the value of the title variable in the template context data. Install this middleware by adding it to MIDDLEWARE_CLASSES in your settings file. Then visit any page in the django admin app you should see the title of the page change to We changed the title.
I've solved my problem creating a custom template tag. I'm just wondering on how to add a context variable using a process_template_reponse in a middleware.
精彩评论