Django学习之全局变量

首先说说什么叫全局变量,我们经常在html中使用{{ var }}这样的模板变量,这些变量是我们在视图函数中

提前定义好的变量,通过render()等方法传递到模板中。

但是,还有一类变量,我们并没有在views.py中定义,也能在html中使用该变量,像这样的变量,就叫做

全局变量。

下面来看看如何定义全局变量:

思路:

新建contexts.py文件-->修改settings.py文件-->在html中使用。

1.首先我们需要在项目根目录下的同名目录建立contexts.py文件

复制代码
     1    #!/bin/bash/python 
     2    # -*- coding: utf-8 -*-
     3    # 全局变量
     4    #
     5    from django.conf import settings
     6    
     7    def lang(request):
     8      return {'lang': settings.LANGUAGE_CODE}
复制代码

2.修改settings.py中的全局变量templates

复制代码
    61                'context_processors': [
    62                    'django.template.context_processors.debug',
    63                    'django.template.context_processors.request',
    64                    'django.contrib.auth.context_processors.auth',
    65                    'django.contrib.messages.context_processors.messages',
    66                    'blog.contexts.lang',
    67                ],
复制代码

上述中'blog.contexts.lang'即是我们定义的方法

3.在模板中使用

 <h3>全局变量lang:{{ lang }}</h3>
 <h3>是否登录:{{request.user.is_authenticated}}</h3>
request.user.is_authenticated为系统自带的全局变量。
tips:
在views.py中必须使用render()或其他能够定向到模板的方法,像HttpResponse()就不行!
附:页面图

settings.py 

SITE_NAME = “站点名称”

SITE_DESC = "站点描述"

views.py

from django.shortcuts import render
from django.conf import settings


def global_settings(request):
return {
'SITE_NAME': settings.SITE_NAME,
'SITE_DESC': settings.SITE_DESC
}


def index(request):
return render(request, 'index.html', locals())

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.global_settings'
],
},
},
]

index.html
<h1>{{ SITE_NAME }}</h1>
<h1>{{ SITE_DESC }}</h1>


---------------------
作者:wawa8899
来源:CSDN
原文:https://blog.csdn.net/wawa8899/article/details/52107755
版权声明:本文为博主原创文章,转载请附上博文链接!

原文地址:https://www.cnblogs.com/ExMan/p/9812418.html