Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'folder.settings') do?

Tags:

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?

like image 720
Eric Kim Avatar asked May 14 '18 13:05

Eric Kim


People also ask

What does OS environ Setdefault do?

environ. setdefault(key, default) is guaranteed to modify the dictionary exactly the same way as os.

What is Django Conf settings?

django. conf settings are django default or "global" settings which you may override with your own project based settings.

What is the use of settings py in Django?

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.

Where is Django settings file?

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 .


2 Answers

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搭建及源码分析(二)

like image 87
Zacama Avatar answered Oct 26 '22 04:10

Zacama


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/

like image 40
Siva Prasad Avatar answered Oct 26 '22 06:10

Siva Prasad