this my middleware code :
JavaScript
x
12
12
1
from django.conf import settings
2
from django.template import RequestContext
3
4
class BeforeFilter(object):
5
def process_request(self, request):
6
settings.my_var = 'Hello World'
7
request.ss = 'ssssssssss'
8
return None
9
def process_response(self, request, response):
10
11
return response
12
this is the settings.py:
JavaScript
1
8
1
TEMPLATE_CONTEXT_PROCESSORS = (
2
'django.core.context_processors.request',
3
)
4
MIDDLEWARE_CLASSES = (
5
6
'middleware.BeforeFilter',
7
)
8
and the view is :
JavaScript
1
14
14
1
#coding:utf-8
2
3
from django.conf import settings
4
from django.shortcuts import render_to_response
5
6
from django.http import HttpResponse
7
from django.template import RequestContext
8
9
10
def index(request):
11
context = RequestContext(request)
12
context['a'] = 'aaaa'
13
return render_to_response('a.html',context)
14
the html is :
JavaScript
1
2
1
{{a}}fffff{{ss}}
2
but it not show {{ss}}:
JavaScript
1
2
1
aaaafffff
2
so how do i show :
JavaScript
1
2
1
aaaafffffssssssss
2
how to insert some text in all django context using django middleware,
so that i cant use to insert the text everytime ,
thanks
Advertisement
Answer
To meet your initial goal, I do not think the BeforeFilter middle ware is required. What we need is just a template context processor.
Write a context processor as following:
JavaScript
1
5
1
#file: context_processors.py
2
3
def sample_context_processor(request):
4
return {'ss':'ssssssssss'} #or whatever you want to set to variable ss
5
then add the context processor to TEMPLATE_CONTEXT_PROCESSORS list
JavaScript
1
6
1
#file: settings.py
2
3
TEMPLATE_CONTEXT_PROCESSORS = (
4
'myproject.context_processors.sample_context_processor',
5
)
6