4

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'>.

David Buck
  • 3,752
  • 35
  • 31
  • 35
Micah Pearce
  • 1,805
  • 3
  • 28
  • 61

3 Answers3

8

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
Ali
  • 2,541
  • 2
  • 17
  • 31
  • 2
    I don't understand how this is the accepted answer. You just confirmed what he said in the question, not explained why the difference! – Joel Wigton Jul 14 '21 at 22:45
5

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.

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
0

project DIR --|app DIR --|settings.py <<< your variable API_KEY = '28234-jns-23-23n'

from app.settings import API_KEY
Shane Cheek
  • 143
  • 2
  • 12