Django中全局Context处理器

1.模板标签和模板变量

   模板标签在{% %}中定义:

{% if is_logged_in %}
    Thanks for logging in!
{% else %}
    Please log in.
{% endif %}

  模板变量在 {  }中定义:

My first name is {{ first_name }}. My last name is {{ last_name }}.

2.Context处理器和 RequestContext处理器

context 是一个传递给模板的名称到值的映射(类似Python字典)。通过从context获取值来替换模板中变量并执行所有的模板标签来实现模板渲染。

from django.template import loader, Context

def view_1(request):
    # ...
    t = loader.get_template('template1.html')
    c = Context({
        'app': 'My app',
        'user': request.user,
        'ip_address': request.META['REMOTE_ADDR'],
        'message': 'I am view 1.'
    })
    return t.render(c)

def view_2(request):
    # ...
    t = loader.get_template('template2.html')
    c = Context({
        'app': 'My app',
        'user': request.user,
        'ip_address': request.META['REMOTE_ADDR'],
        'message': 'I am the second view.'
    })
    return t.render(c)

在上述代码中定义了两个视图,他们除了message不同其余信息都相同,而这样分别定义显然是冗余的。所以需要引入 RequestContext处理器。

from django.shortcuts import render_to_response
from django.template import RequestContext

def custom_proc(request):   # context处理器,它接收一个 HttpRequest 对象,然后返回一个字典
    "A context processor that provides 'app', 'user' and 'ip_address'."
    return {
        'app': 'My app',
        'user': request.user,
        'ip_address': request.META['REMOTE_ADDR']
    }

def view_1(request):
    # ...
    return render_to_response('template1.html',
        {'message': 'I am view 1.'},
        context_instance=RequestContext(request, processors=[custom_proc])) # 接受processors参数

def view_2(request):
    # ...
    return render_to_response('template2.html',
        {'message': 'I am the second view.'},
        context_instance=RequestContext(request, processors=[custom_proc]))

上述代码中利用 render_to_response 代替了render使得可以不用手动载入模板。值得注意的是,在上面这种方法中虽然看似减少了冗余代码,但是由于需要不断键入processors参数,所以依然不够简洁。

所以djang提供对全局 context 处理器的支持。在settings.py 中,有类似代码:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(BASE_DIR, 'templates')
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [   # 以下定义了默认的全局文本处理器
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'blog.views.custom_proc',  # 见下文代码
            ],
        },
    },
]

以下方法实现全局化文本处理器。

  • 建议在项目的应用(app)或项目(project)下创建一个叫做context_processors.py的文件。只要它们存放在你的Python的搜索路径中,它们放在哪个物理路径并不重要,这样你可以在CONTEXT_PROCESSORS设置里指向它们。
  • 在context_processors.py中创建你需要定义的处理器,使每个context处理器完成尽可能小的功能。
  • 将该文本处理器引入到 context_processors 目录下,如上文代码。

       特别的,不去额外定义 context_processors.py ,而在 views.py 中直接写好 custom_proc 后,则可以将其目录加入到  context_processors 中。eg:上述代码中的 def custom_proc(request):

3.  调用 settings.py 中的配置信息作为全局调用

  •    在 settings.py 中加入你要替换的信息:    
SITE_NAME = '。。。的个人博客'
SITE_DESC = 'Python开发 && Django开发'
  •     在 views.py 中引入参数:
from django.conf import settings
def global_setting(request):
    return {'SITE_NAME': settings.SITE_NAME,
            'SITE_DESC': settings.SITE_DESC,}
  • 在 settings.py 中 TEMPLATE的文本处理器中加入
    'blog.views.global_setting',

至此,这种方法也不需要在render 或 render_to_response 中指明 context 或 RequestContext 就可以直接在HTML模板中利用模板变量来进行渲染。

相比之下,还是方法2中较简单。

原文地址:https://www.cnblogs.com/king-lps/p/7291248.html