django中settings.py中变量的全局引用图解

高洛峰
Release: 2017-03-28 16:08:18
Original
1618 people have browsed it

在settings.py中添加自定义变量,可以通过setting.(点)变量名的方式访问,如:

from django.conf import settings
site_name = settings.SITE_NAME
site_desc = settings.SITE_DESC
Copy after login

但是,如果遇到了一些频繁访问的变量,如:邮箱,网站标题,网站的描述,这样访问就很不方便,解决方法:

1.首先在settings.py中添加对应的变量:

#网站信息SITE_NAME="hupeng的个人博客"SITE_DESC="pyhon爱好者,希望和大家一起学习,共同进步"
Copy after login

2.在view中定义函数,返回包含settings配置文件中的变量

from django.conf import settings
def global_settings(request):    
return {"SITE_NAME": settings.SITE_NAME,            
"SITE_DESC": settings.SITE_DESC}
Copy after login

注意:

函数中需要添加参数request,否则会出现以下错误:

django中settings.py中变量的全局引用图解

3.在setting.py中的TEMPLATES中的OPTIONS配置项中添加global_settings函数

django中settings.py中变量的全局引用图解

 4.修改模板,通过键名的方式直接访问对应的变量

django中settings.py中变量的全局引用图解

5.最终效果:

django中settings.py中变量的全局引用图解

The above is the detailed content of django中settings.py中变量的全局引用图解. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!