开发者

how to insert some text in all django context using django middleware

this my middleware code :

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

this is the settings.py:

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.core.context_processors.request',
)
MIDDLEWARE_CLASSES = (
    ...
    'middleware.BeforeFilter',
)

and the view is :

#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)

the html is :

{{a}}fffff{{ss}}

but it not show {{ss}}:

aaaafffff 

so how do i show :

开发者_如何学C
aaaafffffssssssss

how to insert some text in all django context using django middleware,

so that i cant use to insert the text everytime ,

thanks


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:

#file: context_processors.py

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

then add the context processor to TEMPLATE_CONTEXT_PROCESSORS list

#file: settings.py 

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


You need to specify that you accessing request in the template. If you do just {{ss}} the variable does not exist since it an attribute of request (you did request.ss = 'ssssssssss', right?). So do {{request.ss}} in your template and it should work.


The OP asked for how to do this with middleware but I found this question without needing that requirement. The currently accepted answer is outdated and the edit queue is full.

As of Django 1.10, the TEMPLATE_CONTEXT_PROCESSORS setting has been moved to the context_processors option of TEMPLATES.

context_processors is a list of dotted Python paths to callables that are used to populate the context when a template is rendered with a request. These callables take a request object as their argument and return a dict of items to be merged into the context. It defaults to an empty list.

# context_processors.py

def sample_context_processor(request):
    return {'key': 'value'}

# settings.py

TEMPLATES = [
    {
        'OPTIONS': {
            'context_processors': [
                'myproject.context_processors.sample_context_processor',
            ],
        },
    },
]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜