万里长征第二步——django个人博客(第三步 —— 设置一些全局变量)

  1. 可以将一些全局变量设置在settingg.py里
    #网站的基本信息配置
    SITE_NAME = 'John的个人博客'
    SITE_DESC = '专注学习Python开发,欢迎和大家交流'
    WEIBO_SINA = 'http://weibo.sina.com/664390'
    WEIBO_TENCENT = 'http://weibo.qq.com/664390'
    PRO_RSS = 'http://www.baidu.com'
    PRO_EMAIL = '664390905@qq.com'

     

  2. 设置views.py文件,使模板可以调用这些变量
    from django.conf import settings  #调用settings
    # Create your views here.
    def global_setting(request):   #把setting方法读取出来
    return {
    'SITE_NAME': settings.SITE_NAME,   #返回定义的信息
    'SITE_DESC': settings.SITE_DESC,
         }

     

  3. 再回到setting.py,,设置上下文处理器 TEMPLATES
    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.global_setting',
                ],
            },
        },
    ]

     

  4. 最后直接在模板index.html中直接调用这些变量
    <header>
    <div class="logo">
    <h1>{{SITE_NAME}}</h1>
    <p>{{SITE_DESC}}</p>
    </div>

     

posted on 2016-05-29 16:36  不蜚又不鸣  阅读(2569)  评论(2编辑  收藏  举报

导航