Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django settings: How to access variables from the settings folder in an app

I have a Django project with the following structure:

--|src
  --project
  --|settings
     --__init__.py
     --production.py
     --local.py
  --|app1

In my app I import the settings (from django.conf import settings) and then as I was following a tutorial they said to do this getattr(settings, VARIABLE). That doesn't work for me. Instead I can do this: settings.VARIABLE. What's the difference?

Oh and I ran type(settings) and it outputted <class 'django.conf.LazySettings'>.

like image 526
Micah Pearce Avatar asked Dec 23 '22 05:12

Micah Pearce


2 Answers

in order to access variables in settings.py file, you can do like this:

for example, I define STATIC_ROOT variable in settings.py file like this:

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static', 'static_root')

and I can access to this variable like this:

from django.conf import settings
document_root=settings.STATIC_ROOT
like image 143
Mohammad Ali Avatar answered Dec 28 '22 07:12

Mohammad Ali


The difference is that for various reasons (see the documentation for details), the settings object is not loaded unless an object is referenced from it.

The LazySettings object is special and you have to access it with settings.SOMETHING.

The reason its called "Lazy" is because the entire object is not loaded and made available to you when you import it. This LazySettings object acts like a proxy to the actual settings object.

like image 33
Burhan Khalid Avatar answered Dec 28 '22 07:12

Burhan Khalid