Django Tutorial

Django Create A Complete Project

Django Template

Django Database Query

Django Form

Django Authentication and Permission Management

Django unittest

Django Advanced

Django settings.py Configuration File

The settings.py file is an important component of a Django project, as it contains configuration settings that affect the behavior and functionality of your application. In this tutorial, we will discuss key settings and how to modify them.

  • Open your Django project's settings.py file, located in the project's main directory (e.g., myproject/settings.py).

  • Debug mode: The DEBUG setting controls whether your application is running in debug mode. When DEBUG = True, Django will provide detailed error pages and will not cache templates or static files. In a production environment, set DEBUG = False to improve performance and security.

DEBUG = True
  • Allowed hosts: The ALLOWED_HOSTS setting specifies a list of valid hostnames for your application. In a production environment, you should add the domain names or IP addresses of your server(s).
ALLOWED_HOSTS = ['example.com', 'www.example.com', '192.168.1.1']
  • Middleware: The MIDDLEWARE setting is a list of middleware classes that process requests and responses in your application. Middleware classes are executed in the order they are listed.
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.XContentOptionsMiddleware',
]
  • Database: The DATABASES setting configures the database connections for your application. By default, Django uses the SQLite database. To use a different database (e.g., PostgreSQL, MySQL, or Oracle), update the ENGINE and other required settings.
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'mydatabase',
        'USER': 'myuser',
        'PASSWORD': 'mypassword',
        'HOST': 'localhost',
        'PORT': '',
    }
}
  • Time zone: The TIME_ZONE setting specifies the default time zone for your application. Set this to the appropriate time zone for your project.
TIME_ZONE = 'UTC'
  • Installed apps: The INSTALLED_APPS setting is a list of Django applications that are enabled for your project. These applications provide functionality such as authentication, the admin interface, and session management. Add your custom applications to this list to enable them.
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp',
]
  • Static files: The STATIC_URL setting specifies the base URL for serving static files, such as CSS, JavaScript, and images. The STATICFILES_DIRS setting is a list of directories where Django looks for static files. In a production environment, use the STATIC_ROOT setting to specify a directory where the collectstatic management command will gather all static files.
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
  1. Django settings.py File Explained:

    • Description: The settings.py file in Django contains configuration settings for the entire project. It covers database settings, middleware, security, and more.
    • Code: Example of a basic settings.py file structure:
      # settings.py
      DEBUG = True
      DATABASES = {...}
      INSTALLED_APPS = [...]
      
  2. Django settings.py Environment Variables:

    • Description: Use environment variables to configure sensitive information dynamically, promoting security and flexibility.
    • Code:
      # settings.py
      import os
      
      SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY')
      
  3. Django settings.py Database Configuration:

    • Description: Configure the database connection details in settings.py, specifying the database engine, name, user, and password.
    • Code: Example of configuring a PostgreSQL database:
      # settings.py
      DATABASES = {
          'default': {
              'ENGINE': 'django.db.backends.postgresql',
              'NAME': 'mydatabase',
              'USER': 'mydatabaseuser',
              'PASSWORD': 'mypassword',
              'HOST': 'localhost',
              'PORT': '5432',
          }
      }
      
  4. Django settings.py DEBUG Mode:

    • Description: The DEBUG setting in settings.py controls whether the application is in debugging mode, influencing error handling and display.
    • Code: Toggle the DEBUG setting based on the environment:
      # settings.py
      DEBUG = os.environ.get('DJANGO_DEBUG', 'False') == 'True'
      
  5. Django settings.py Template Configuration:

    • Description: Configure template-related settings in settings.py, such as template engines, directories, and context processors.
    • Code: Example of configuring the Django template engine:
      # settings.py
      TEMPLATES = [
          {
              'BACKEND': 'django.template.backends.django.DjangoTemplates',
              'DIRS': [os.path.join(BASE_DIR, 'templates')],
              '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',
                  ],
              },
          },
      ]
      
  6. Django settings.py Middleware Configuration:

    • Description: Middleware settings in settings.py define the order and behavior of middleware components.
    • Code: Example of adding custom middleware:
      # settings.py
      MIDDLEWARE = [
          'myapp.middleware.CustomMiddleware',
          # ...
      ]
      
  7. Django settings.py Static Files Configuration:

    • Description: Configure static files settings in settings.py to specify the location for static files like CSS, JavaScript, and images.
    • Code: Example of configuring static files:
      # settings.py
      STATIC_URL = '/static/'
      STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
      
  8. Django settings.py Logging Configuration:

    • Description: Logging settings in settings.py control how the application logs messages, errors, and warnings.
    • Code: Example of configuring logging:
      # settings.py
      LOGGING = {
          'version': 1,
          'disable_existing_loggers': False,
          'handlers': {
              'file': {
                  'level': 'DEBUG',
                  'class': 'logging.FileHandler',
                  'filename': '/path/to/django/debug.log',
              },
          },
          'loggers': {
              'django': {
                  'handlers': ['file'],
                  'level': 'DEBUG',
                  'propagate': True,
              },
          },
      }
      
  9. Django settings.py Secret Key:

    • Description: The SECRET_KEY setting in settings.py is a cryptographic key used for security purposes.
    • Code: Example of setting the SECRET_KEY:
      # settings.py
      SECRET_KEY = 'mysecretkey'
      
  10. Django settings.py Custom Configuration Variables:

    • Description: Define custom configuration variables in settings.py for project-specific settings.
    • Code:
      # settings.py
      MY_CUSTOM_SETTING = 'myvalue'