Django Settings
Django settings are the values that shape a project. They live in one module, named settings.py.
The settings file
This file holds three settings. Each line names one value.
DEBUG = True
SECRET_KEY = "key"
SITE_NAME = "My Blog"Read a setting in a view
The view reads SITE_NAME from the settings. The page shows the site name.
from django.conf import settings
def home(request):
return HttpResponse(settings.SITE_NAME)Read two settings
This code prints the site name and the DEBUG value. Both come from the settings.
print(settings.SITE_NAME)
print(settings.DEBUG)Example
import django
from django.conf import settings
settings.configure(DEBUG=True, SECRET_KEY="key", ROOT_URLCONF=__name__, ALLOWED_HOSTS=["*"], SITE_NAME="My Blog")
django.setup()
from django.http import HttpResponse
from django.urls import path
def home(request):
return HttpResponse(settings.SITE_NAME)
urlpatterns = [path("", home)]
from django.test import Client
client = Client()
print(client.get("/").content.decode())
print(settings.SITE_NAME)
print(settings.DEBUG)
Key points
- settings.py holds one value per line, in capital letters.
- DEBUG turns the debug pages on or off.
- SECRET_KEY is a secret value the project keeps private.
- A view reads a setting with settings.NAME.
In this example, the setup lines configure Django. The settings carry a custom value, SITE_NAME. The home view reads it from the settings. The test client asks for the home page. The prints show the page, the site name, and the DEBUG value.
Note
Never share SECRET_KEY or put it in public code.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
How does a view read the SITE_NAME setting?