Home > Backend Development > Python Tutorial > Detailed example of global reference of variables in settings.py of Django development

Detailed example of global reference of variables in settings.py of Django development

Y2J
Release: 2017-04-28 09:33:58
Original
1639 people have browsed it

When some content in the website, such as email, website title, website description, we can store these things in the database or in our settings file. This article mainly introduces settings.py in django. The relevant information on the global reference of variables is introduced in great detail in the article. Friends in need can refer to it.

This article mainly introduces the relevant information about the global reference of variables in settings.py in django. I won’t say much below, let’s take a look at the detailed introduction.

Preface

Add custom variables in settings.py, which can be accessed by setting. (dot) the variable name, such as:

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

However, if you encounter some frequently accessed variables, such as: email, website title, website description, such access will be very inconvenient.

The solution is as follows:

1. First, add the corresponding variables in settings.py:

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

2. Define a function in the view and return the variable containing the settings configuration file

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

Note:The parameter request needs to be added to the function, otherwise the following error will occur:

Detailed example of global reference of variables in settings.py of Django development

3. Add the global_settings function to the OPTIONS configuration item in TEMPLATES in setting.py

Detailed example of global reference of variables in settings.py of Django development

4. Modify the template , directly access the corresponding variable through the key name

Detailed example of global reference of variables in settings.py of Django development

5. Final effect:

Detailed example of global reference of variables in settings.py of Django development

Summarize

The above is the detailed content of Detailed example of global reference of variables in settings.py of Django development. 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 admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template