[英]how to insert some text in all django context using django middleware
這是我的中間件代碼:
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上下文中插入一些文本,
所以我不能每次都插入文本,
謝謝
為了實現您的初始目標,我認為不需要BeforeFilter中間件。 我們需要的只是模板上下文處理器 。
編寫上下文處理器如下:
#file: context_processors.py
def sample_context_processor(request):
return {'ss':'ssssssssss'} #or whatever you want to set to variable ss
然后將上下文處理器添加到TEMPLATE_CONTEXT_PROCESSORS列表中
#file: settings.py
TEMPLATE_CONTEXT_PROCESSORS = (
'myproject.context_processors.sample_context_processor',
)
您需要指定在模板中訪問request
。 如果只做{{ss}}
變量不存在,因為它是request
的屬性(你做了request.ss = 'ssssssssss'
,對吧?)。 因此,請在模板中{{request.ss}}
進行操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.