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

zjm*_*126 13 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
    def process_response(self, request, response):

        return response
Run Code Online (Sandbox Code Playgroud)

这是settings.py:

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.core.context_processors.request',
)
MIDDLEWARE_CLASSES = (
    ...
    'middleware.BeforeFilter',
)
Run Code Online (Sandbox Code Playgroud)

而且观点是:

#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)
Run Code Online (Sandbox Code Playgroud)

HTML是:

{{a}}fffff{{ss}}
Run Code Online (Sandbox Code Playgroud)

但它没有显示{{ss}}:

aaaafffff 
Run Code Online (Sandbox Code Playgroud)

那我怎么展示:

aaaafffffssssssss
Run Code Online (Sandbox Code Playgroud)

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

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

谢谢

xia*_*o 啸 27

为了实现您的初始目标,我认为不需要BeforeFilter中间件.我们需要的只是模板上下文处理器.

编写上下文处理器如下:

#file: context_processors.py

def sample_context_processor(request):
   return {'ss':'ssssssssss'} #or whatever you want to set to variable ss
Run Code Online (Sandbox Code Playgroud)

然后将上下文处理器添加到TEMPLATE_CONTEXT_PROCESSORS列表中

#file: settings.py 

TEMPLATE_CONTEXT_PROCESSORS = (
    'myproject.context_processors.sample_context_processor',
)
Run Code Online (Sandbox Code Playgroud)

  • OP询问如何使用django中间件而不是模板上下文处理器来做到这一点 (2认同)