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

Time:2019-10-17

1. Configuration template file

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',
            ],
            #Build the template label into the template https://docs.djangoproject.com/en/2.1/topics/templates/
            '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 settings.py file

    DATABASES = {
        'default': {
            'engine': 'Django. DB. Backends. MySQL', ා database engine
            'name': 'tzproject', ා database name
            'user':'dj'user ','user name'
            'password': 'Python VIP', ා password
            'host': '127.0.0.1', 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:

    [client]
    database = tzproject
    user = dj_user
    password = pythonvip
    host = 127.0.0.1
    port = 3306
    default-character-set = utf8


    Introduce db.cnf in the settings.py file

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'OPTIONS':{
                'read_default_file': 'utils/db/db.cnf',
            }
        }
    }


    Official documents:https://docs.djangoproject.com/en/2.1/ref/databases/#connecting-to-the-database

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 https://pypi.doubanio.com/simple

2. Install pymysql

#Install pymysql
pip install pymysql -i https://pypi.doubanio.com/simple

  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 settings.py file

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/0",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    },
    'session': {
        'BACKEND': 'django_redis.cache.RedisCache',
        'LOCATION': 'redis://127.0.0.1:6379/1',
        'OPTIONS': {
            'CLIENT_CLASS': 'django_redis.client.DefaultClient',
        }
    },
}

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

Document address:https://django-redis-chs.readthedocs.io/zh_CN/latest/

Django document:https://docs.djangoproject.com/en/2.2/topics/http/sessions/#using-cached-sessions

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

Diary
LOGGING = {
    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,
            Diary文件个数
            '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 settings.py file.
logger = logging.getLogger('django')    

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

Official documents:https://docs.djangoproject.com/en/2.2/topics/logging/#module-django.utils.log

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/'
STATICFILES_DIRS = [
    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 ../manage.py startapp news
(tzproject) ~/code/tztz/apps$ python ../manage.py startapp course
(tzproject) ~/code/tztz/apps$ python ../manage.py startapp doc
(tzproject) ~/code/tztz/apps$ python ../manage.py 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

INSTALLED_APPS = [
    # ...
    'user',
    'news',
    'doc',
    'course'
]

 

Recommended Today

Single and multiple buttons are styled with pictures

I’ve always seen people asking how to style and enlarge the buttons of radio buttons and multi buttons? Let’s share an example I did. 1. First make the button into a picture  2.html page Copy code The code is as follows: <!DOCTYPE HTML> <html> <head> <meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ /> <script type=”text/javascript” src=”jquery-1.10.2.min.js”></script> <script type=”text/javascript”> […]