Python Django's settings Py parsing

Posted by The Bat on Fri, 31 Dec 2021 14:19:20 +0100

Novice on the road, please help correct the mistakes in the article. The information in the article is compiled from English websites and videos, and some translations may also need correction. Thank you in advance!

"""
Django settings for myFirstDjango project.

Generated by 'django-admin startproject' using Django 3.1.

For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
  • settings. The PY file is automatically generated when the Django admin startproject {project name} command is run.
  • The code in the file is settings Py automatically generated settings, we do not need to use all parts, but there can be increases or decreases.
    settings.py's official English Introduction: https://docs.djangoproject.com/en/3.1/topics/settings/
    All settings and their values: https://docs.djangoproject.com/en/3.1/ref/settings/

The following section is to set the project root directory (root) path: (the two versions contacted are slightly different)

Django 3.1
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve(strict=True).parent.parent
  • import os is not required
  • Path(__file__) Will get the path of the current file__ file__ Is a variable indicating the file path, which can be used to obtain the path of the current file or the imported file.
  • . resolve(strict=True): if the path does not exist and strict is True, a FileNotFoundError exception (raise error) will be thrown.
Django 1.10/1.11
import os

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  • os is a module that allows us to interact with the underlying operating system. In the Django project, we can find the path of the project root directory by importing the os module.
  • You can use OS path. Dirname() gets the upper level path name of the path
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '-*&6&x*****************************sj_9_m*a5u*e'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []
  • SECRET_KEY: the key automatically created when you first run Django admin start project
    • This key will provide an encrypted signature to provide a certain security guarantee for data transmission in non secure channels (most of the time, the network is not secure)
    • If the digital encryption signature matches the key, it will allow the user to accept all transmitted data, so do not disclose the key
    • The key must be stored in settings Py file, otherwise an improvyconfigurederror error will be thrown.
  • DEBUG: when set to True, the amount of error reporting information will be large, so in Production environment (prod env) It's best to turn it off, but it should be turned on Error log
  • ALLOWED_HOST: setting the domain name that allows you to see the web page can prevent the web site from being presented on the user's computer with different names. Set ALLOWED_HOST can prevent hackers from changing the headers of the website Header attack
# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',  # Authenticate
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

INSTALLED_APPS: Django framework is our pre installed application

  • We need to add our own application creation here, such as setting Py to find these applications. These applications are usually created in the project root directory and settings Py peer.
    • An application can be understood as a plug-in that provides help to a project
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',
]

MIDDLEWARE:middleware It is the software that connects the underlying system software and application software and facilitates the communication between software components

ROOT_URLCONF = 'myFirstDjango.urls'

The path to the wsgi file, which contains the application. (with explanation)

# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}
  • Default database for our project
  • sqlite3 is a lightweight database in the development environment. It's best not to use it in the production environment
# Password validation
# https://docs.djangoproject.com/en/3.1/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',
    },
]
  • These are auxiliary applications to help verify passwords.
  • When the project is just created, the project will not check the set password, so users can use any password. These are just provided here for our future use.
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

LANGUAGE_CODE: the language used in the project. The default here is American English

USE_I18N: internationalization. I18N means that different languages and localizations (L10N) are supported when Internationalization(I+18 letters + n) is set to True.
USE_L10N: localization. L10N means that when Localization(L+10 letters + n) is set to True, the internationalized version can be changed according to different local cultures.

  • I18N and I10N are not substitutes and can be seen as allowing internationalization and opening up the option of localization. Internationalization can set some general changes, but localization is the key to truly combine the project with local culture.
  • Example: I18N allows the use of Arabic, but Arabic is written from right to left, and the project does not design the version with the right in front. At this time, L10N is required to realize this function. ( source)

USE_TZ: do you want to use timezone in your project

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/

STATIC_URL = '/static/'

When setting up a template, we need to set the location of these static files (HTML, CSS, JAVASCRIPT) and use static_ URLs can find their paths.

Topics: Python Django