Home >Backend Development >Python Tutorial >Detailed example of global reference of variables in settings.py of Django development
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
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爱好者,希望和大家一起学习,共同进步"
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}
Note:The parameter request needs to be added to the function, otherwise the following error will occur:
3. Add the global_settings function to the OPTIONS configuration item in TEMPLATES in setting.py
4. Modify the template , directly access the corresponding variable through the key name
5. Final effect:
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!