Python 如何使用django中间件在所有django上下文中插入一些文本

Python 如何使用django中间件在所有django上下文中插入一些文本,python,django,templates,Python,Django,Templates,这是我的中间件代码: from django.conf import settings from django.template import RequestContext class BeforeFilter(object): def process_request(self, request): settings.my_var = 'Hello World' request.ss = 'ssssssssss' return None

这是我的中间件代码:

from django.conf import settings
from django.template import RequestContext

class BeforeFilter(object):
    def process_request(self, request):
        settings.my_var = 'Hello World'
        request.ss = 'ssssssssss'
        return None
    def process_response(self, request, response):

        return response
这是settings.py:

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.core.context_processors.request',
)
MIDDLEWARE_CLASSES = (
    ...
    'middleware.BeforeFilter',
)
这种观点是:

#coding:utf-8

from django.conf import settings
from django.shortcuts import render_to_response

from django.http import HttpResponse 
from django.template import RequestContext


def index(request):
    context = RequestContext(request)
    context['a'] = 'aaaa'
    return render_to_response('a.html',context)
html是:

{{a}}fffff{{ss}}
但它不显示{{ss}:

aaaafffff 
那么,我如何展示:

aaaafffffssssssss
如何使用django中间件在所有django上下文中插入一些文本

所以我不能每次都插入文本


谢谢

您需要指定在模板中访问
请求
。如果只执行
{{ss}
操作,则该变量不存在,因为它是
request
的属性(您执行了
request.ss='ssssss'
,对吗?)。因此,在模板中使用
{{request.ss}
,它应该可以工作。

为了达到最初的目标,我认为不需要BeforeFilter中间件。我们所需要的只是一个

编写上下文处理器,如下所示:

#file: context_processors.py

def sample_context_processor(request):
   return {'ss':'ssssssssss'} #or whatever you want to set to variable ss
然后将上下文处理器添加到模板\u上下文\u处理器列表中

#file: settings.py 

TEMPLATE_CONTEXT_PROCESSORS = (
    'myproject.context_processors.sample_context_processor',
)

OP询问如何使用django中间件,而不是模板上下文处理器,可以在模板中像这样访问{{ss}。我还想用中间件进行一些数据注入。但是HttpResponse和TemplateResponse让我同时使用了它们:|