Django creates a project, explains the configuration of settings, configures the mysql database, and migrates the database.

This blog introduces how to build your first Django project and improve this project. Please understand if there are any shortcomings. Introduce how to create a project, explain the configuration of setting, configure the mysql database, and migrate the database.

   工具:   pycharm2020
   <Django 从入门到 ‘放弃’ >  第二篇
   沙漏在下雨

This column introduces how I went from getting started with Django to `giving up`. There are basic and complicated projects. I will spend my own money to go to training classes to share with you. Let's study together! This is the first time I have published a series of tutorials. Please advise me on the shortcomings. I am a junior preparing for the postgraduate entrance examination party!


Create the first project (project):

  • Use the command line, or use pycharm below terminal

Insert picture description here

  • After the creation is successful, open the file tree.

Insert picture description here

  • Ignore the nowapp project app first. Once created, open the subfolder nowproject. There are some more configuration files in it. The introduction is as follows:

    1) manage.py file

    The manage.py file in the first-level subdirectory is an important command line tool for managing Django projects. It is mainly used to start projects, create applications, and complete database migration.

    2) init .py file

    Two subdirectories of the init .py file directory for identifying the current location is a Python package, if in this file, or by other methods import introducing Django packets will be automatically identified.

    3) settings.py file

    The settings.py file is an important configuration file for the Django project. When the project starts, the settings.py configuration file will be automatically called, and some of the globals it defines provide parameters for Django operation. You can also customize some variables in this configuration file for data transfer in the global scope.

    4) urls.py file

    The url.py file is used to record the URL mapping relationship of the Django project. It belongs to the basic routing configuration file of the project. The routing system is configured in this file. The dynamic path in the project must be matched by this file before the Web Access to resources on the site.

    5) wsgi.py file

    wsgi.py is the entry file of the WSGI (Web Server Gateway Interface) server program, mainly used to start the application. It complies with the WSGI protocol and is responsible for the realization of the network communication part. It is only used when the project is deployed.

    6) asgi.py file

    The asgi.py file is the asgi configuration of the django project. It exposes the callable ASGI as a module-level variable named "application". For more information about this file, see https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/

Run your django project:

Enter the following commands in the command line:

py manage.py runserver

Insert picture description here

After successful startup, Django's own database file db.sqlite3 will be generated in this directory, which is a lightweight database that Django comes with by default. Visit the created project through http://127.0.0.1:8000, 8000 is Django's default port number. Finally, if you want to exit the running state, you can terminate it by pressing CTRL+C.

Click on this domain name link and it is successfully created as follows:

Insert picture description here

This means that you have created the project and successfully ran it. At this time, you will find that the command line is constantly refreshing entries. This means that Django is generally in a running state, so that it can be real-time during project development. Test or debug the code.

If you want to run on other port numbers:

py manage.py runserver 8080

Or run on other computers in the LAN:
py manage.py runserver 0.0.0.0:8080


manage.py file command:

In the console we enter py manage.py helpsome help message is printed:

Some of these commands will be used later, and they are not required to be mastered.

Type 'manage.py help ' for help on a specific subcommand.

Available subcommands:

[auth]
    changepassword
    createsuperuser

[contenttypes]
    remove_stale_contenttypes

[django]
    check
    compilemessages
    createcachetable
    dbshell
    diffsettings
    dumpdata
    flush
    inspectdb
    loaddata
    makemessages
    makemigrations
    migrate
    sendtestemail
    shell
    showmigrations
    sqlflush
    sqlmigrate
    sqlsequencereset
    squashmigrations
    startapp
    startproject
    test
    testserver

[sessions]
    clearsessions

[staticfiles]
    collectstatic
    findstatic
    runserver

Setting file explains configuration:

The setting file is an important configuration file of the Django framework. Some global variables it defines are used to pass parameters to the Django framework. We can also modify this file according to our actual needs to achieve certain specific requirements. Let's introduce this configuration file in detail. Understanding this configuration file is an important step into the Django world.

1) BASE_DIR

It is used to bind the absolute path where the current project BookStore is located. All files in the project need to rely on this path. The method of binding the path is as follows:

BASE_DIR=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

__file__It is the syntax of Python, displays the location of the current file, and the os.path.abspath(__file__)method returns the absolute path of the current file.

2) SECRET_KEY

The essence of this variable is an encrypted key, which is generally used in conjunction with the encryption algorithm Hash and MD5. For example, SECRET_KEY is needed to encrypt user passwords or sessionid used when establishing a session. In the actual development work, it is generally saved in the environment variable of the system to ensure the security of the encryption key.

3) DEBUG

There are two ways to configure the enable mode of Django project:

  • DEBUG = True is used in the development environment and belongs to the debugging mode. Some error messages will be exposed during the running of the project to facilitate debugging.
  • DEBUG = False is used in the online environment, which means that the debug mode is not enabled.

When we write the code, set it to True.

4) ALLOWED_HOSTS

Used to configure the domain name (IP address) that can access the current site. When DEBUG = False, it must be filled in. There are three ways to use it:

  • [], an empty list, means that only 1217.0.0.1 and localhost can access this project;
  • ['*'], which means that any network address can access the current project;
  • ['192.168.1.3', '192.168.3.3'] means that only the current two hosts can access the current project.

Tip: If you are in a local area network, so that other hosts can also access this site, you should use the ALLOWED_HOSTS=['*'] method.

5) INSTALLED_APPS

This parameter refers to the list of applications (APP) used to install in the current project. Django puts the default built-in applications in this list, such as the Admin background application, Auth user management system, etc. We also used these two modules before They are introduced accordingly, and they are called "applications" in Django.

We can add or delete them according to our own project requirements. For example, if the company wants to develop a back-end management system separately, you can comment out the first item admin. Applications written by yourself during development must be registered in this variable table to take effect. So this list needs frequent changes.

For example, in our project, we need to register the application.

INSTALLED_APPS = [
‘django.contrib.admin’,
‘django.contrib.auth’,
‘django.contrib.contenttypes’,
‘django.contrib.sessions’,
‘django.contrib.messages’,
‘django.contrib.staticfiles’,
‘你的应用’,
]

6) MIDDLEWARE

It is used to register middleware, and Django loads some middleware by default. For example, SessionMiddleware for processing sessions, MessageMiddleware for processing messages, etc. We can also add or comment on these middleware. Later we can also write our own middleware extension hook function for extension.

7) ROOT_URLCONF

ROOT_URLCONF = 'nowproject.urls'

It specifies the root URL of the current project and is the entry point of Django's routing system.

8) TEMPLATES

It is used to specify the configuration information of the template. Each element in the list is a dictionary. The following is Django's default template engine:

TEMPLATES = [
    {
    
    
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [], # 在这里我们可以设置自己的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',
            ],
        },
    },
]

9) WSGI_APPLICATION

WSGI_APPLICATION = 'BookStore.wsgi.application'

When the project is deployed, the full Python path of the WSGI application object that Django's built-in server will use.

10) DATABASES

DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } 

It is used to specify database configuration information. The default configuration here is the sqllite3 database that comes with Django. Django supports multiple databases. Change the database configuration in this dictionary variable. In the following chapters, we will explain the Mysql database configuration.

11) AUTH_PASSWORD_VALIDATORS

This is a pluggable password validator that can be configured for multiple at a time. Django uses these built-in components to avoid the problem of insufficient password levels set by users.

AUTH_PASSWORD_VALIDATORS = [ 
    
    {
    
            'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',    }, 
    {
    
            'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',   },  
    {
    
            'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',  },
]

12) LANGUAGE_CODE和TIME_ZONE

They represent the language configuration items and the configuration items of the current server time zone respectively. Our commonly used configurations are as follows:

  • The value of LANGUAGE_CODE is English:'en-us' or Chinese:'zh-Hans';
  • The value of TIME_ZONE is the world time zone'UTC' or the Chinese time zone'Asia/Shanghai'.

So we need to change the TIME_ZONE setting to the Chinese time zone (zh-Hans) and change the LANGUAGE_CODE setting to Chinese (Asia/Shanghai) , otherwise the database storage time will be less than 8 hours, because it is the East Eight District.

13) USE_118N和USE_L10N

After the project is developed, you can choose to provide services to users in different countries, so you need to support internationalization and localization. The values ​​of the two variables USE_118N and USE_L10N indicate whether to enable the internationalization and localization functions. The state is turned on by default.

Tips: USE_I18N = True and USE_L10N = True, the I18N refers to the internationalized English abbreviation, and L10N refers to the localized English abbreviation.

14) USE_TZ=True

It refers to the processing method of the time zone. When set to True, the time stored in the database is the world time'UTC '. When TIME_ZONE is set, USE_TZ needs to be set == False .

15) STATIC_URL= ‘/static/’

It refers to the storage location of static resources, which include CSS, JS, and Images. For example, we need to add some pictures to the project. Usually these static pictures are stored in the static directory of the newly created (in the same directory as the app), so that access to the static resources through the STATIC_URL='/static/' path is realized , We will open a chapter to explain this later.


Django configuration mysql database:

First make sure you have installed the mysql database correctly, the installation is successful, and create a database in your database.

create database django;

Then enter the DATABASES in the setting and set as follows:

DATABASES = {
    
    
    'default': {
    
    
        'ENGINE': 'django.db.backends.mysql',  # 指定使用的数据库引擎,可以通过 Django.db.backends 来查看哪些数据库可以与 Django 配合使用;
        'NAME': 'django',  # 数据库名字
        'USER': "root",  # mysql 用户名称
        'PASSWORD': '123123',  # 数据库的密码
        'HOST': "127.0.0.1",  # 数据库服务地址, 这里我们是测试开发 填本地地址 
        'PORT': 3306,   # mysql 对应的端口号 
        'default-character-set': "UTF8",  # 设置编码规则 utf8 
    }

}

Then you need to install the pymysql library pip install PyMySQL

Finally, add a piece of code to the __init__ file at the same level of setting:

import pymysql 
pymysql.install_as_MySQLdb()

This completes the configuration of the mysql database, and the data we created will be correctly saved to the local mysql file and can be viewed correctly.

Database migration:

When we create a project, cmd will print some error warnings, indicating that we have not performed data migration. "Migration" means to migrate the data tables of Django's default application to our own database. The operation is as follows:

py manage.py migrate

After running, we can print MySQL information through cmd to get:

Insert picture description here

​ We also need to use a command, because if the current data field changes, then we get the wrong form,

​ Use commands

python manage.py makemigrations

1) makegrations generate database migration file

​ When the data table is changed, we first execute the makemigrations command, and then Django will regenerate a new database migration file to record the difference between the table structure, the naming rule is to add 1 to the serial number of the previous migration file, such as 0002_xxx , 0003_xxx.

2) migrate to perform database migration command

​ After that, execute the migrate command again to make the new migration file effective and synchronize back to the database, thereby completing the modification of the table structure definition. For built-in Django applications, the database migration file has been generated, so just use the migrate command directly.

3) complete database migration summary

​ Every time the data table is changed, the following two commands need to be executed, and their execution order is as follows:

​ python manage.py makemigrations
​ python manag.py migrate

These are the commands that we will execute after creating a new modle form, to prevent forgetting.

The above is about how to create a project in Django, explain the configuration of the setting, and the configuration of the database and the migration of the database.

Add 1 to the number, such as 0002_xxx, 0003_xxx.

2) migrate to perform database migration command

​ After that, execute the migrate command again to make the new migration file effective and synchronize back to the database, thereby completing the modification of the table structure definition. For built-in Django applications, the database migration file has been generated, so just use the migrate command directly.

3) complete database migration summary

​ Every time the data table is changed, the following two commands need to be executed, and their execution order is as follows:

​ python manage.py makemigrations
​ python manag.py migrate

These are the commands that we will execute after creating a new modle form, to prevent forgetting.

The above is about how django creates a project, explains the configuration of the setting, and configures the mysql database and the database migration operation.

This column introduces how I got from getting started with Django 放弃. There are basic and complicated projects. I will spend my own money to go to training courses to share with you. Let's study together! This is the first time I have published a series of tutorials. Please advise me on the shortcomings. I am a junior preparing for the postgraduate entrance examination party!

Guess you like

Origin blog.csdn.net/qq_45906219/article/details/109392318