SoFunction
Updated on 2025-04-13

Files in Django use full parsing

This article introduces the tutorial on each configuration item in Django file in detail, covering the role and best practices of core configuration items

1. Basic configuration

1. ​BASE_DIR

BASE_DIR = Path(__file__).resolve().
  • Function: The project root directory path, used to build other paths (such as templates, static file paths)
  • ^Note: It is safer to use Path objects, replacing traditional ()

2. ​SECRET_KEY

SECRET_KEY = 'django-insecure-xxxxxxxx'

Function: Used for encrypted signatures (Session, password reset, etc.)

Safety advice

  • Never submit to version control
  • Production environment loads using environment variables:
import os
SECRET_KEY = ('DJANGO_SECRET_KEY')

DEBUG = True
  • Function: Turn on debug mode (display detailed error page)
  • The production environment must be closed
DEBUG = False

4. ALLOWED_HOSTS

ALLOWED_HOSTS = ['', '127.0.0.1']
  • Function: Whitelist of domain names/IPs allowed
  • Development environment configuration
ALLOWED_HOSTS = ['*']  # Development environment only!

2. Applications and middleware

1. ​INSTALLED_APPS

# Register a built-in, third-party, and own appINSTALLED_APPS = [
    '', # Management backend    '', # Certification System    '', # Provide a general model relationship system that allows dynamic correlation between arbitrary models    '', #Session Management    '', # Provide a one-time messaging system to temporarily store prompt information between page jumps (such as operation success/failure prompt)    '', # Static file processing    '',  # Customize the application    'rest_framework',         # Third-party applications]

2. ​MIDDLEWARE

# Register built-in, third-party, and own written middlewareMIDDLEWARE = [
    '', # Security related header information    '', #Session Management    '',
    '', # CSRF Protection    '', User Authentication
     '',
    '',
]

3. Database configuration

1. ​DATABASES

DATABASES = {
    'default': {
        'ENGINE': '',
        'NAME': 'mydatabase',
        'USER': 'mydbuser',
        'PASSWORD': 'mypassword',
        'HOST': 'localhost',
        'PORT': '5432',
    }
}

Supported database engines:

  • sqlite3: Lightweight local database (for development)
  • postgresql:PostgreSQL
  • mysql:MySQL
  • oracle:Oracle

2. Use environment variables (production recommendation)

import os
DATABASES = {
    'default': {
        'ENGINE': '',
        'NAME': ('DB_NAME'),
        'USER': ('DB_USER'),
        'PASSWORD': ('DB_PASSWORD'),
        'HOST': ('DB_HOST'),
        'PORT': ('DB_PORT'),
    }
}

4. Static files and media files

1. ​STATIC_URL & STATIC_ROOT

STATIC_URL = '/static/'  # Access URL prefixSTATIC_ROOT = BASE_DIR / 'staticfiles'  # collectstatic collection directorySTATICFILES_DIRS = [      # Extra static file directory    BASE_DIR / 'static',
]

2. MEDIA_URL & MEDIA_ROOT

MEDIA_URL = '/media/'     # User uploads file access pathMEDIA_ROOT = BASE_DIR / 'media'  # File storage path

V. Template configuration

1. TEMPLATES

TEMPLATES = [
    {
        'BACKEND': '',
        'DIRS': [BASE_DIR / 'templates'],  # Template search path        'APP_DIRS': True,  # Whether to search for the templates directory in the application        'OPTIONS': {
            'context_processors': [
                '.context_processors.debug',
                '.context_processors.request',
                '.context_processors.auth',
                '.context_processors.messages',
            ],
        },
    },
]

6. International configuration

1. Language and time zone

LANGUAGE_CODE = 'zh-hans'  # ChineseTIME_ZONE = 'Asia/Shanghai'
USE_I18N = True            # Enable internationalizationUSE_TZ = True              # Use time zone

2. Multilingual support

LOCALE_PATHS = [BASE_DIR / 'locale']  # Translate file directory

7. Safety configuration (production required)

1. HTTPS settings

SECURE_SSL_REDIRECT = True         # Force HTTPSSESSION_COOKIE_SECURE = True       # Security CookiesCSRF_COOKIE_SECURE = True           # CSRF Cookie EncryptionSECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

2. Security header information

SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_BROWSER_XSS_FILTER = True
X_FRAME_OPTIONS = 'DENY'  # Prevent click hijacking

8. Advanced configuration

1. Cache configuration

CACHES = {
    'default': {
        'BACKEND': '',
        'LOCATION': 'redis://127.0.0.1:6379/1',
    }
}

2. Email configuration

EMAIL_BACKEND = ''
EMAIL_HOST = ''
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'user@'
EMAIL_HOST_PASSWORD = 'password'

9. Best Practices

1. Environment separation: Use multiple configuration files

settings/
├── 
├── 
└── 

2. Sensitive information management: Use python-dotenv

from dotenv import load_dotenv
load_dotenv()

3. Performance optimization:

DATABASES['default']['CONN_MAX_AGE'] = 300  # Database connection pool

expand:

Through reasonable configuration, you can:

  • Ensure safe isolation between development and production environments
  • Optimize web application performance
  • Flexible extension functions (such as caching, mail services)
  • Implement multilingual support and international deployment

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.