Django全局变量实现方式 2015-03-06 23:00

介绍

每一个页面都需要读取一个全局变量,采用什么方法,对代码侵入性最小?
答案:采用TEMPLATE_CONTEXT_PROCESSORS。

配置

  • 准备

创建文件:house/util.py 内容如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import logging
from house.models import SystemStatus

logger = logging.getLogger(__name__)

from django.conf import settings as _settings
def settings(request):
    """
    TEMPLATE_CONTEXT_PROCESSORS
    """
    context = { 'settings': _settings }
    user = request.user
    try:
        #..... 这里设置全局变量
        system_status = SystemStatus.objects.all()[0]
        context['system_status'] = system_status
        logger.info("set system status variable")
    except Exception,e:
        log.error("settings:%s" % e)
    return context

项目全局配置文件settings.sh

新增"house.util.settings"

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
TEMPLATE_CONTEXT_PROCESSORS = (
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    "django.core.context_processors.static",
    "django.core.context_processors.tz",
    "django.contrib.messages.context_processors.messages",
    "django.core.context_processors.request",
    "house.util.settings" # new add
)

模板文件

1
2
<li><span class="navbar-text">数据更新日期:  </span></li>
<li><span class="navbar-text">{{ system_status.last_update }}</span></li>

参考文档

Django全局变量的几种方式中的方法2。

Tags: #Django    Post on Python