I am taking an online Django class now, and I don't understand some of the configuration code. My instructor says that the following code is required in a Python code that populates my database.
import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ProTwo.settings') import django django.setup()
I don't understand what this code is doing at all, except that the second argument in setdefault()
is referring to my app's settings.py
file.
What is DJANGO_SETTINGS_MODULE
? What does it do? Why is it passed in as an arg in setdefault()
?
And what does django.setup()
do? What does it change?
environ. setdefault(key, default) is guaranteed to modify the dictionary exactly the same way as os.
django. conf settings are django default or "global" settings which you may override with your own project based settings.
settings.py is a core file in Django projects. It holds all the configuration values that your web app needs to work; database settings, logging configuration, where to find static files, API keys if you work with external APIs, and a bunch of other stuff.
A Django settings file doesn't have to define any settings if it doesn't need to. Each setting has a sensible default value. These defaults live in the module django/conf/global_settings.py .
First look at os.environ.setdefault()
, environ is an instance of class _Environ
, which inherits from IterableUserDict
, and IterableUserDict
inherits from UserDict
, including setdefault()
.
This method is also a method of UserDict
, take a look at the functions implemented by setdefault
.
def setdefault(self, key, failobj=None): if key not in self: self[key] = failobj return self[key]
The key is DJANGO_SETTINGS_MODULE
, where self is a dictionary to determine if the key is inside, and do a key-value binding if it is not inside. Then return.
And here is the original link: Django搭建及源码分析(二)
In some cases, you might want to bypass the DJANGO_SETTINGS_MODULE
environment variable. For example, if you’re using the template system by itself, you likely don’t want to have to set up an environment variable pointing to a settings module.
In these cases, you can configure Django’s settings manually.
https://docs.djangoproject.com/en/2.1/topics/settings/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With