Django project: Project Environment Building — II. Django project setting


1. Configuration template file

        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
            #Build the template label into the template
            'builtins': ['django.templatetags.static'],


2. Configure MySQL database

  1. Create database

    mysql> create database tzproject charset=utf8mb4;
    Query OK, 1 row affected (0.00 sec)
  2. Create user
    mysql> create user 'dj_user'@'%' identified by 'pythonvip';
    Query OK, 1 row affected (0.00 sec)
  3. To grant authorization
    mysql> grant all privileges on tzproject.* to 'dj_user'@'%';
    Query OK, 0 rows affected (0.03 sec)
    mysql> flush privileges;
    Query OK, 0 rows affected (0.02 sec)
    #Authorization creation write together
    grant all privileges on tzproject.* to 'xinlan'@'%' identified by 'pythonvip'
  4. Configure settings

    Method 1: directly add the database configuration information in the file

        'default': {
            'engine': 'Django. DB. Backends. MySQL', ා database engine
            'name': 'tzproject', ා database name
            'user':'dj'user ','user name'
            'password': 'Python VIP', ා password
            'host': '', host IP
            'port': 3306 ා port

    Method 2: save the database configuration information to a file, and introduce it into the settings file. (recommended)

    New database profiledb.cnf(name at will)

    Db.cnf file content:

    database = tzproject
    user = dj_user
    password = pythonvip
    host =
    port = 3306
    default-character-set = utf8

    Introduce db.cnf in the file

        'default': {
            'ENGINE': 'django.db.backends.mysql',
                'read_default_file': 'utils/db/db.cnf',

    Official documents:

3. Install the python driver of MySQL database

⚠⚠⚠⚠⚠⚠⚠⚠⚠⚠⚠⚠⚠⚠⚠⚠⚠⚠⚠⚠⚠⚠⚠⚠⚠⚠⚠⚠__init__.pyImport pymysql from.


1. Install mysqlclient

#Update Ubuntu first
sudo apt-get update 

#Then according to the dependency Library
sudo apt-get install default-libmysqlclient-dev

#Switch to virtual environment again
workon tzproject

#Finally, install mysqlclient
pip install mysqlclient -i

2. Install pymysql

#Install pymysql
pip install pymysql -i

  staysettings.pyIn the directory where the file is located__init__.pyImport



The first method is recommended.mysqlclientFaster and safer, official recommendation.

4. Configure redis cache

It is used to store user session information and various information to be cached.

#Install Django redis in virtual machine
pip install django-redis
#Redis configuration specified in file

    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
    'session': {
        'BACKEND': 'django_redis.cache.RedisCache',
        'LOCATION': 'redis://',
        'OPTIONS': {
            'CLIENT_CLASS': 'django_redis.client.DefaultClient',

#Session storage cache settings
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'

Document address:

Django document:

5. Configure loggers

It is used to record various log information during system operation.

Create a logs folder in the root directory of the project to hold the log files

    Chinese version
    'version': 1,
    #Disable existing loggers
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '{levelname} {asctime} {module} {lineno:d} {message}',
            'style': '{',
        'simple': {
            'format': '{levelname} {module} {lineno:d} {message}',
            'style': '{',
    'filters': {
        'require_debug_true': {
            '()': 'django.utils.log.RequireDebugTrue',
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'filters': ['require_debug_true'],
            'class': 'logging.StreamHandler',
            'formatter': 'simple'
        'file': {
            'level': 'INFO',
            #This handler can record a set of log files
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': os.path.join(BASE_DIR, 'logs/tz_django.log'),
            #Maximum bytes of single log file
            'maxBytes': 300*1024*1024,
            'backupCount': 10,
            'formatter': 'verbose'
    'loggers': {
        'django': {
            'handlers': ['console', 'file'],
            'level': 'INFO',  Diary器接收的最低级别
            'propagate': True,

Usage method

#How to use
# import the logging library
import logging

# Get an instance of a logger
#Django here is the logger name defined in loggers under the logging configuration in the file.
logger = logging.getLogger('django')    

def my_view(request, arg1, arg):
    if ***:
        # Log an error message
        logger.error('Something went wrong!')

Official documents:

6. Time zone configuration

#Modify language
LANGUAGE_CODE = 'zh-hans'
#Modify time zone
TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_L10N = True
#Use time zone
USE_TZ = True

7. Static file configuration

Create a static directory in the root directory of the project to store static files (CSS, JS, image, font, etc.)

STATIC_URL = '/static/'
    os.path.join(BASE_DIR, 'static')

8. Create application

This project is mainly composed of four modules: news article module, course video playing module, document downloading module, user management module, etc. Create an apps directory under the root directory of the project to store the sub applications.


Then CD to the apps directory to create sub applications

~$ cd ~/code/tztz/apps/
~/code/tztz/apps$ workon tzproject
(tzproject) ~/code/tztz/apps$ python ../ startapp news
(tzproject) ~/code/tztz/apps$ python ../ startapp course
(tzproject) ~/code/tztz/apps$ python ../ startapp doc
(tzproject) ~/code/tztz/apps$ python ../ startapp user

In the settings file, add the following settings

import sys

#After creating the application, add the apps directory to sys.path
sys.path.insert(0, BASE_DIR)
sys.path.insert(1, os.path.join(BASE_DIR, 'apps'))

Then right-click the apps folder and the project root folder respectively, add them to the source root, and optimize the import path (pycharm prompt).



Finally, add the app to the installed? Apps list

    # ...