› Forums › Web Development › HarvardX: CS50W – CS50’s Web Programming with Python and JavaScript › CS50W – Lecture 3 – Django › Understanding Django’s settings.py File (Complete Beginner’s Guide)
- This topic is empty.
-
AuthorPosts
-
June 13, 2026 at 5:16 am #6888
When students begin learning Django, one of the first files they encounter is
settings.py.This file acts as the central configuration hub of a Django project. Almost everything Django needs to know about the project is configured here, including:
- Installed applications
- Database settings
- Templates
- Middleware
- Security settings
- Static files
- Internationalization
- Authentication rules
The following is the complete
settings.pyfile generated for the CS50W Wiki project.Complete settings.py Code
""" Django settings for wiki project. Generated by 'django-admin startproject' using Django 3.0.2. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '%710m*zic)#0u((qugw#1@e^ty!c)9j04956v@ly(_86n$rg)h' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'encyclopedia', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'wiki.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'wiki.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_URL = '/static/'
What Is settings.py?
Think of
settings.pyas the project’s control panel.When Django starts, it reads this file and learns:
- Which apps exist
- Where templates are located
- Which database to use
- How security should work
- Which middleware should run
- How static files should be served
Without
settings.py, Django would not know how to operate.
Importing the os Module
import osPython’s
osmodule allows interaction with the operating system.Django uses it extensively to build file paths.
For example:
os.path.join("folder", "file.txt")produces:
folder/file.txtor
folder\file.txtdepending on the operating system.
This helps Django work on Windows, Linux, and macOS.
Understanding BASE_DIR
BASE_DIR = os.path.dirname( os.path.dirname( os.path.abspath(__file__) ) )This is one of the most important lines in the file.
Suppose the project structure is:
wiki/ │ ├── manage.py ├── db.sqlite3 │ └── wiki/ ├── settings.py ├── urls.py ├── wsgi.py__file__refers to:wiki/settings.pyStep 1
os.path.abspath(__file__)returns:
/home/user/wiki/wiki/settings.pyStep 2
os.path.dirname(...)returns:
/home/user/wiki/wikiStep 3
os.path.dirname(...)returns:
/home/user/wikiThis becomes:
BASE_DIRwhich points to the root project folder.
Later Django uses it to locate files such as:
db.sqlite3
SECRET_KEY
SECRET_KEY = '%710m*zic)#0u((qugw#1@e^ty!c)9j04956v@ly(_86n$rg)h'The secret key is used for cryptographic operations.
Examples include:
- Session security
- Password reset tokens
- CSRF protection
- Cookie signing
Think of it as Django’s master security password.
Development
SECRET_KEY = 'some-random-string'is fine.
Production
It should:
- Never be shared
- Never be committed publicly
- Usually be stored in environment variables
DEBUG
DEBUG = TrueThis tells Django whether it is running in development mode.
DEBUG=True
Django shows detailed error pages.
Example:
TypeError at /wikialong with:
- File names
- Line numbers
- Tracebacks
This is extremely useful while learning.
DEBUG=False
Used in production.
Users see friendly error pages instead of sensitive debugging information.
ALLOWED_HOSTS
ALLOWED_HOSTS = []This controls which domains can access the project.
Development:
ALLOWED_HOSTS = []works because Django automatically allows localhost.
Production examples:
ALLOWED_HOSTS = [ "example.com", "www.example.com" ]This prevents host-header attacks.
INSTALLED_APPS
INSTALLED_APPS = [ 'encyclopedia', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ]This list tells Django which applications exist.
Think of each app as a mini project inside the larger project.
encyclopedia
'encyclopedia'This is the CS50W app.
Without this entry Django would not load:
- Views
- Templates
- URLs
- Models
from the encyclopedia app.
django.contrib.admin
'django.contrib.admin'Provides Django’s admin dashboard.
Example:
/admin
django.contrib.auth
'django.contrib.auth'Provides:
- Login
- Logout
- User accounts
- Password hashing
- Permissions
django.contrib.contenttypes
Supports Django’s content type framework.
Allows Django to track different model types.
django.contrib.sessions
Enables sessions.
Example:
request.sessioncan store information between requests.
django.contrib.messages
Provides flash messages.
Example:
messages.success(request, "Saved!")
django.contrib.staticfiles
Manages:
- CSS
- JavaScript
- Images
MIDDLEWARE
MIDDLEWARE = [ ... ]Middleware sits between:
Browser ↓ Middleware ↓ Viewand again on the way back.
View ↓ Middleware ↓ BrowserEach middleware performs a specific task.
SecurityMiddleware
'django.middleware.security.SecurityMiddleware'Adds security-related protections.
SessionMiddleware
'django.contrib.sessions.middleware.SessionMiddleware'Loads session data.
CommonMiddleware
'django.middleware.common.CommonMiddleware'Handles common HTTP operations.
CsrfViewMiddleware
'django.middleware.csrf.CsrfViewMiddleware'Protects forms from CSRF attacks.
Example:
{% csrf_token %}works because of this middleware.
AuthenticationMiddleware
'django.contrib.auth.middleware.AuthenticationMiddleware'Makes available:
request.userinside views.
MessageMiddleware
'django.contrib.messages.middleware.MessageMiddleware'Enables Django messages.
XFrameOptionsMiddleware
'django.middleware.clickjacking.XFrameOptionsMiddleware'Protects against clickjacking attacks.
ROOT_URLCONF
ROOT_URLCONF = 'wiki.urls'Tells Django where the main URL routes live.
Specifically:
wiki/urls.py
TEMPLATES
TEMPLATES = [...]Configures Django’s template engine.
BACKEND
'BACKEND': 'django.template.backends.django.DjangoTemplates'Uses Django’s built-in template engine.
DIRS
'DIRS': []No extra template directories are configured.
APP_DIRS
'APP_DIRS': TrueTells Django to automatically search:
app_name/templates/inside each installed app.
For example:
encyclopedia/templates/
Context Processors
These automatically add variables into templates.
Example:
request user messagesbecome available without manually passing them.
WSGI_APPLICATION
WSGI_APPLICATION = 'wiki.wsgi.application'WSGI stands for:
Web Server Gateway InterfaceIt allows web servers and Python applications to communicate.
Production servers such as:
- Gunicorn
- uWSGI
use this entry.
DATABASES
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } }Defines database configuration.
ENGINE
'django.db.backends.sqlite3'Uses SQLite.
Advantages:
- No installation
- Beginner friendly
- Single file database
NAME
os.path.join(BASE_DIR, 'db.sqlite3')Builds:
project_root/db.sqlite3This is where all data is stored.
AUTH_PASSWORD_VALIDATORS
AUTH_PASSWORD_VALIDATORS = [...]These improve password security.
UserAttributeSimilarityValidator
Prevents passwords too similar to:
username email
MinimumLengthValidator
Requires minimum password length.
CommonPasswordValidator
Rejects common passwords.
Examples:
password 123456 qwerty
NumericPasswordValidator
Rejects passwords containing only numbers.
Example:
123456789
Internationalization Settings
LANGUAGE_CODE
LANGUAGE_CODE = 'en-us'Sets the default language.
TIME_ZONE
TIME_ZONE = 'UTC'Sets the default timezone.
Examples:
'UTC' 'Asia/Kolkata' 'Europe/London'
USE_I18N
USE_I18N = TrueEnables translation support.
USE_L10N
USE_L10N = TrueEnables locale-specific formatting.
Examples:
- Dates
- Times
- Numbers
USE_TZ
USE_TZ = TrueStores times with timezone awareness.
Highly recommended.
STATIC_URL
STATIC_URL = '/static/'Defines the URL prefix for static files.
Example:
<link rel="stylesheet" href="/static/styles.css">Django knows to look inside static directories.
Static files include:
- CSS
- JavaScript
- Images
- Icons
How Django Uses settings.py During a Request
When a user visits:
http://127.0.0.1:8000/wiki/PythonDjango roughly performs these steps:
- Load settings from
settings.py - Load installed apps
- Activate middleware
- Read URL configuration
- Find matching view
- Execute view
- Load templates
- Access database if needed
- Generate HTML response
- Send response back to browser
Throughout this process, Django repeatedly consults
settings.py.
Key Takeaway
settings.pyis the brain of a Django project.It controls:
- Project paths (
BASE_DIR) - Security (
SECRET_KEY,DEBUG) - Allowed domains (
ALLOWED_HOSTS) - Installed applications (
INSTALLED_APPS) - Middleware pipeline (
MIDDLEWARE) - URL configuration (
ROOT_URLCONF) - Templates (
TEMPLATES) - Database connections (
DATABASES) - Password security (
AUTH_PASSWORD_VALIDATORS) - Localization (
LANGUAGE_CODE,TIME_ZONE) - Static files (
STATIC_URL)
A beginner can think of
settings.pyas the file that answers the question:“How should Django run this project?”
Every time the Django server starts, one of the first things it does is read
settings.pyand configure itself according to the instructions found there. -
AuthorPosts
- You must be logged in to reply to this topic.
