0

I know how to access the settings module (as detailed here) but I have a number of custom settings modules that extend settings.py and I'm not sure how to access it in my view. It's available in my template but I can't find any information on how to access it in the settings. os.environ["DJANGO_SETTINGS_MODULE"] correctly returns the string of my intended settings module, but since it's just a string it doesn't have my variables on it.

custom_settings1.py

from settings import *  # noqa: F403

SITE_ID = 1
SITE_NAME = "MY SITE"
Community
  • 1
  • 1
thumbtackthief
  • 6,093
  • 10
  • 41
  • 87

3 Answers3

0

To use settings in a view, you just import it as in the cited post.

def settings_view(request):
    from django.conf import settings
    context = { 
        'settings': settings
    }
    return render(request, 'template.html', context)

And in your template:

My setting is {% settings.my_setting %}
2ps
  • 15,099
  • 2
  • 27
  • 47
0

In my project, I use a custom context processor to inject settings variables into my templates. This way you don't have to add it to the context of every view function/class.

# app/context.py
from django.conf import settings


def my_settings(request):
    return { 'MY_CUSTOM_SETTING': settings.MY_CUSTOM_SETTING }

Then you add it to your context processors in the the TEMPLATE setting.

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                ...
                'app.context.my_settings',
            ],
        },
    },
]

Now it is available in any template!

{{ MY_CUSTOM_SETTING }}
Brobin
  • 3,241
  • 2
  • 19
  • 35
0

Far from being a "common use case", you have this exactly the wrong way round.

Almost always, you will define custom settings directly in settings.py; that way they are added to the object you get when you do from django.conf import settings.

Very occasionally you might want to define settings in separate modules; in which case, you import them from there into the main settings.py, not the other way round as you have them.

settings.py is the canonical place for settings to go.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895