An example of using Django's own background management system for database management

The background management system that comes with Django is mainly used to operate and manage the database. It is a powerful feature of the Django framework that allows you to quickly create an admin interface for managing your application's data model.

Using the Django background management system, you can easily perform the following operations:

  1. Database management: You can view, add, edit and delete records in the database without writing a custom management interface or database query statements.

  2. Model management: The Django background management system will automatically detect the models you define in the application and create a corresponding management interface for each model. In this way, you can directly operate the model on the background management interface.

  3. User rights management: The Django background management system supports user authentication and rights control. You can restrict specific users from accessing and operating data by defining user groups and rights.

  4. Customize the management page: Although the Django background management system provides many default functions, you can also customize the management page according to your needs, adding custom functions and views.

Overall, the Django background management system is a powerful tool that makes it easy and efficient to operate and manage the database, which allows developers to focus more on business logic and function development without spending a lot of time on the management interface and energy.

In this article, we create a data table model related to product classification and product information in Django, and use Django's own background management system to manage the data tables of product classification and product information.

01-Create a new Project named "good_info"

The command is as follows:

CD E:\Python_project\P_001\myshop-test
E:
django-admin startproject good_info

02-Create two new applications

Execute the following commands to create two applications in sequence:

CD E:\Python_project\P_001\myshop-test\good_info\
E:
python manage.py startapp goods
python manage.py startapp users

The above two applications are mainly goods. We will write the database class model of product classification and product information in the models.py of goods.
However, since the product information contains user information, a users model is also required.
insert image description here

03- Register two applications in settings.py

The code for registration in settings.py is as follows:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'users',
    'goods',
]

04-Write the database model classes of the two applications

04-01-users model creation and detailed code explanation

Open the file: E:\Python_project\P_001\myshop-test\myshop_background\apps\users\apps.py
and write the following code:

from datetime import datetime
from django.db import models
from django.contrib.auth.models import AbstractUser, Group, Permission


class MyUser(AbstractUser):
    SEX = (
        (0, '男'),
        (1, '女'),
    )
    LEVEL = (
        (1, '寂寞卡会员'),
        (2, '钻石卡会员'),
        (3, '金卡会员'),
        (4, '银卡会员'),
    )
    STATUS = (
        (0, '正常'),
        (1, '异常'),
    )

    groups = models.ManyToManyField(
        Group,
        verbose_name='groups',
        blank=True,
        help_text='The groups this user belongs to.',
        related_name='user_groups'  # 设置不同的 related_name
    )
    user_permissions = models.ManyToManyField(
        Permission,
        verbose_name='user permissions',
        blank=True,
        help_text='Specific permissions for this user.',
        related_name='user_permissions'  # 设置不同的 related_name
    )

    truename = models.CharField('真实姓名', blank=True, max_length=50)
    mobile = models.CharField('手机号码', max_length=11, default="")
    sex = models.IntegerField(default=0, choices=SEX)
    birthday = models.DateField(blank=True, null=True)
    user_img = models.ImageField("头像", upload_to="user_img", default="")
    level = models.IntegerField(default=4, choices=LEVEL)
    status = models.IntegerField(default=0, choices=STATUS)
    create_time = models.DateTimeField(default=datetime.now, verbose_name='创建时间')
    update_time = models.DateTimeField(default=datetime.now, verbose_name="更新时间")

    def __str__(self):
        return self.username

    class Meta(AbstractUser.Meta):
        permissions = (
            ['check_myuser', '审核用户信息'],
        )

① Description of the fields groups and field user_permissions.
The fields groups and user_permissions are actually useless, so why define them? Please see the blog post for the reason: https://blog.csdn.net/wenhao_ir/article/details/131773627

②Q: Can you introduce from django.contrib.auth.models import AbstractUserthe class AbstractUser involved in the code?
Answer: In the Django framework, django.contrib.auth.modelsmodules provide related functions for authentication and authorization. Among them, AbstractUserthe class is the abstract base class of Django's default user model (user model). For details, please refer to the link: https://blog.csdn.net/wenhao_ir/article/details/131594115

blank=True,③ What does the code truename=models.CharField('real name', blank=True, max_length=50) mean?
In Django models, blank=Trueis a parameter that indicates whether a model field is nullable or not. At the timeblank=True , the field could be nullable during form validation and no validation errors would be thrown. If blank=False, the field is required during form validation and cannot be empty.

In the code, truenameis a CharField, which represents a character field used to store the real name. Since specified blank=True, this means that fields can be left blank when creating or updating instances of this model truename. This is useful for scenarios where the real name is optional in some cases. But it should be noted that even blank=True, the field value stored in the database can still be an empty string, not NULLa value.

④ What does the default="" in the code mobile=models.CharField('mobile phone number', max_length=11, default="") mean?
Answer: Yes default=""is models.CharFielda parameter that specifies the default value for the field.

default=""Indicates that when a new model instance is created, if no mobilespecific value is provided for the field, then the field will default to an empty string.

In the database, if no value is provided for the field, it will be stored as an empty string instead of NULLa value. This means that when querying and retrieving data, if mobilethe field has not been explicitly assigned a value, it will return the empty string as the default value.

mobileBy setting a default value, you ensure that a field on a model instance always has a default empty string value , even if no value is provided for that field . This may be useful in some cases, such as when the mobile number is an optional field, which can be defaulted to an empty string.

Note: If mobile=models.CharField('手机号码',max_length=11)you don't specify defaultthe parameter or set it to in code default=None, when you create a new model instance, if you don't mobileprovide a concrete value for the field, the field will default to NULLthe value.

⑤Understanding of the statement sex = models.IntegerField(default=0,choices=SEX):
This code choices=SEXdefines a list of options, each of which consists of a value and a corresponding display label. In this example, SEXis a tuple containing tuples, each tuple has two elements, the first is the stored value, and the second is the displayed label.

In the database, sexfields will be stored using integers, not strings. You can use any of these options to indicate gender when creating or updating objects. The corresponding integer value is stored in the database (0 represents male, 1 represents female), but on the interface or other places that need to be displayed, you can use the display labels ('male' and 'female') in the tuple to represent .

That is to say, if I write a value, which is the string 'male', then the integer 0 is written to the database.

⑥ What does upload_to="user_img" in the statement user_img=models.ImageField("Avatar", upload_to="user_img", default="") mean?
Answer: In Django, the upload path can be set through parameters in the definition of the model field upload_to, or it can be set globally through the Django configuration file.

  1. Settings in model fields:
    When defining model fields, upload_toparameters can be used to specify the upload path. For example:

    from django.db import models
    
    class MyModel(models.Model):
        image = models.ImageField(upload_to='my_upload_path/')
    

    In the above code, upload_tothe parameter is set to 'my_upload_path/', indicating that the uploaded file will be saved MEDIA_ROOT/my_upload_path/under the path, where MEDIA_ROOTis the root path of the media file set in the Django configuration file.

  2. Settings in the global configuration file:
    Django also provides a global configuration file settings.pywhere you can set the default upload path. In the configuration file, you can use MEDIA_ROOTand MEDIA_URLtwo settings to define the root path and corresponding URL of uploaded files. For example:

    # settings.py
    
    MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
    MEDIA_URL = '/media/'
    

    In the above configuration, MEDIA_ROOTthe root path of the media file is specified BASE_DIR/media, and MEDIA_URLthe URL corresponding to the path is specified /media/. When no parameter is specified in the model field upload_to, the file will be saved in MEDIA_ROOTthe path set. For BASE_DIRa detailed introduction, please refer to my other blog post: https://blog.csdn.net/wenhao_ir/article/details/131598936

It should be noted that when using MEDIA_ROOTand MEDIA_URLsetting, make sure that the corresponding URL mapping is included in Django's URL configuration so that the uploaded files can be accessed correctly.

⑦ What is the internal class Meta?
For the answer to this question, please see my other blog post https://blog.csdn.net/wenhao_ir/article/details/131600645

04-02-goods model creation and detailed code explanation

04-02-1 - Copy the common folder

Copy the following common folder to the root directory E:\Python_project\P_001\myshop-test\good_info.
https://pan.baidu.com/s/115vpHu68sR3vDJqvBHuFUg?pwd=g9ow
insert image description here
There is a file base_model.py in the common directory:
insert image description here
the content of the file base_model.py is as follows:

from django.db import models


class BaseModel(models.Model):
    """抽象基类"""
    create_time = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    update_time = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        # 指定抽象基类
        abstract = True

Note: The fields "create_time" and "update_time" are defined in this abstract base class.

04-02-2- Code written into the model file goods\models.py

Open the file: E:\Python_project\P_001\myshop-test\good_info\goods\models.py
and enter the following code:

from django.db import models
from datetime import datetime

from users.models import MyUser
from common.base_model import BaseModel


class GoodsCategory(BaseModel):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=50, verbose_name='分类名称', default='')
    parent = models.ForeignKey("self", null=True, blank=True, verbose_name="父类", on_delete=models.DO_NOTHING, related_name="sub_cat")
    is_nav = models.BooleanField(default=False, verbose_name='是否显示在导航栏')
    sort = models.IntegerField(verbose_name='排序')

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '商品分类'
        verbose_name_plural = '商品分类'
        db_table = 'd_goods_category'  # 在数据库中的表名


class Goods(models.Model):
    STATUS = (
        (0, '正常'),
        (1, '下架'),
    )
    name = models.CharField(max_length=50, verbose_name='商品名称', default='')
    category = models.ForeignKey(GoodsCategory, blank=True, null=True, verbose_name='商品分类', on_delete=models.DO_NOTHING)
    market_price = models.DecimalField(max_digits=8, default=0, decimal_places=2, verbose_name='市场价格')
    price = models.DecimalField(max_digits=8, decimal_places=2, default=0, verbose_name='实际价格')
    unit = models.CharField(max_length=10, verbose_name='计量单位', blank=True, null=True)
    click_num = models.IntegerField(default=0, verbose_name="点击数")
    amount = models.IntegerField(default=0, verbose_name="销售量")
    stock_num = models.IntegerField(default=0, verbose_name="库存数")
    fav_num = models.IntegerField(default=0, verbose_name="收藏数")
    goods_desc = models.CharField(max_length=200, verbose_name='商品详情', default='',)
    status = models.IntegerField(default=0, choices=STATUS)
    is_recommend = models.BooleanField(default=False, verbose_name="是否推荐")
    user = models.ForeignKey(MyUser, blank=True, null=True, verbose_name="用户", on_delete=models.DO_NOTHING)
    createDate = models.DateTimeField(default=datetime.now, verbose_name='创建时间')

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '商品信息'
        verbose_name_plural = '商品信息'
        db_table = 'd_goods'  # 在数据库中的表名

For the understanding of the following code, please refer to the blog post https://blog.csdn.net/wenhao_ir/article/details/131708665

parent = models.ForeignKey("self", null=True, blank=True, verbose_name="父类", on_delete=models.DO_NOTHING, related_name="sub_cat")

05-Create database

Database name: goodtest01
Database user name: goodtest01
Database password: aa123456
insert image description here

06- Configure the database information in the setting.py file

Open the file: E:\Python_project\P_001\myshop-test\good_info\good_info\settings.py
and write the following database configuration information:

DATABASES = {
    
    
    'default': {
    
    
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'goodtest01',
        'USER': 'goodtest01',
        'PASSWORD': 'aa123456',
        'HOST': 'localhost',
        'PORT': '3306',
        # 取消外键约束,否则多对多模型迁移报django.db.utils.IntegrityError: (1215, 'Cannot add foreign key constraint')
        'OPTIONS': {
    
    
            "init_command": "SET foreign_key_checks = 0;",
            'charset': 'utf8'
        },
    }
}

insert image description here

07-Create model migration and execute model migration command

First, please open the database.
First, please open the database.
First, please open the database.

Then execute the following command.

CD E:\Python_project\P_001\myshop-test\good_info\
E:
manage.py makemigrations
manage.py migrate

insert image description here

E:\Python_project\P_001\myshop-test\good_info>manage.py makemigrations
Migrations for 'goods':
  goods\migrations\0001_initial.py
    - Create model GoodsCategory
    - Create model Goods
  goods\migrations\0002_goods_user.py
    - Add field user to goods
Migrations for 'users':
  users\migrations\0001_initial.py
    - Create model MyUser

insert image description here

08-Create background administrator user

Run the command below:

CD E:\Python_project\P_001\myshop-test\good_info\
E:
manage.py createsuperuser

insert image description here
From the above process, if you do not specify the username of the administrator, the default is: administrator, and you can also enter the email address of the administrator.
The password I set above is: bb123456

09-Start the background web service and test whether you can log in to the administrator account

Run the following three commands to start:

CD E:\Python_project\P_001\myshop-test\good_info\
E:
python manage.py runserver

insert image description here
Visit the following URL to enter the background login page that comes with Django:
http://127.0.0.1:8000/admin/
insert image description here
Enter the user name (administrator) and password (bb123456), and log in:
insert image description here

10- Configure the Admin background management system

10-1- Configure the goods/app.py file

Put the original code of the goods/app.py file:

from django.apps import AppConfig


class GoodsConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'goods'

Change it to something like this:

from django.apps import AppConfig


class GoodsConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'goods'
    verbose_name = "商品管理"

That is, add the code verbose_name = "商品管理", so that "commodity management" will be displayed in the left menu navigation in the Admin background management system.

10-2-Settings goods/__init__.py file

goods/__init__.py Write the following code in the file :

from .apps import GoodsConfig
default_app_config = 'goods.GoodsConfig'

The explanation of the statement: from .apps import GoodsConfigis as follows:
In Django, it refers to importing a named module (module) or sub-package (sub-package) .appsfrom the current package (package) [also can be understood as the current directory] . appsIn the above code, from .apps import GoodsConfigthe effect is to import the class GoodsConfig from the apps module in the current directory.

.appsUsed to import from the current package GoodsConfig.

Specifically, a Django application (app) is usually a apps.pyPython package that contains files. apps.pyThe file is used to define the configuration class of the Django application, which contains the metadata information of the application, such as the application name, display name, etc. Normally, Django automatically generates appsmodules that you can import to access your application's configuration classes.

Suppose your project structure is as follows:

my_project/
    my_app/
        __init__.py
        apps.py
        models.py
        views.py

In apps.py, you might define an application configuration class similar to the following:

# my_project/my_app/apps.py

from django.apps import AppConfig

class GoodsConfig(AppConfig):
    name = 'my_app'
    verbose_name = 'My Goods Application'

Now, if you want to reference this configuration class in other files GoodsConfig, you can use relative imports, as follows:

# 任何其他.py文件

from .apps import GoodsConfig

# 使用GoodsConfig进行配置或其它操作

Here, .appsdenotes the module my_appin the current package ( ) from which the class appsis then imported GoodsConfig. Note that appsthis name is used by Django to represent the configuration module of the application.

In summary, .appshere is a relative import syntax for referencing appsmodules in the current package, and importing GoodsConfigclasses from them.

About the statement: default_app_config = 'goods.GoodsConfig'The explanation is as follows:
In Django, default_app_configvariables are used to specify the default configuration class of an application. When a Django application is loaded, it looks in the application's apps.pyfiles, and in it looks for AppConfigthe configuration class it inherits from (if any). Django will then use this configuration class to configure the application's behavior and metadata.

However, there may be times when you want to define a configuration class in your application's apps.pyfiles, but don't want Django to automatically use it as the default application configuration. In this case, you can manually specify the default configuration class instead of letting Django automatically recognize it.

In the code you provided, default_app_config = 'goods.GoodsConfig'the effect is to explicitly specify the application goodsto use GoodsConfigas its default configuration class. The advantage of this is that even if Django automatically detects other configuration classes, it will prefer to use them GoodsConfigas the configuration class for this application.

For example, suppose your application goodshas the following structure:

goods/
    __init__.py
    apps.py
    models.py
    ...

apps.pyThe configuration class is defined in GoodsConfig:

# goods/apps.py

from django.apps import AppConfig

class GoodsConfig(AppConfig):
    name = 'goods'
    verbose_name = 'Goods Application'

Then goods/__init__.pyadded default_app_configthe variable in:

# goods/__init__.py

from .apps import GoodsConfig
default_app_config = 'goods.GoodsConfig'

By setting it like this, you can ensure that GoodsConfigit will be used as goodsthe default configuration class of the application. Even if Django auto-discovers other configuration classes, they are ignored and used GoodsConfig.

It should be noted that default_app_configvariables are only valid if they are set before the application is loaded. When Django starts up, it reads the application's __init__.pyfiles, finds default_app_configthe variable, and applies the configuration class specified by it. Therefore, if you modify this file before running Django, make sure default_app_configthat the settings take effect before Django loads the application.

10-3- Configure the admin.py file

Write the following code in the file: E:\Python_project\P_001\myshop-test\good_info\goods\admin.py:

from django.contrib import admin
from goods.models import *


@admin.register(GoodsCategory)
class GoodsCategoryAdmin(admin.ModelAdmin):
    admin.site.site_title = "我的商城-标签页标题"
    admin.site.site_header = "我的商城-页面标题"
    admin.site.index_title = "商城平台管理-后台管理主页标题"
    # 设置列表中显示的字段
    list_display = ['name', 'sort', 'create_time']  # 字段create_time定义在 from common.base_model import BaseModel 中
    # 搜索
    search_fields = ['name', 'parent_id']
    # 过滤
    list_filter = ['name', 'parent_id']
    # 设置每页现实的数据量
    list_per_page = 10
    # 设置排序
    ordering = ['sort']


@admin.register(Goods)
class GoodsAdmin(admin.ModelAdmin):
    # 设置列表中显示的字段
    list_display = ['name', 'market_price', 'price']

@admin.register(GoodsCategory)What does the code mean?
Answer: There are two functions.
①In Django, @admin.register()it is a decorator (decorator), which is used to register the database model class (Model) to the background management interface. Specifically, @admin.register(GoodsCategory)the function of this line of code is to GoodsCategoryregister the database model class to the Django background management interface, allowing you to manage and operate the model in the background.

Once @admin.register()a database model class is registered via , Django automatically creates a corresponding admin page that allows you to view, add, modify, and delete instances of the model. In this way, you can easily manage GoodsCategorythe data in your database in the background management interface.

②In the above code, GoodsCategoryAdminthe class is used as GoodsCategorythe management class of the model, which it inherits from admin.ModelAdmin. By defining different properties and methods in this class, you can customize the appearance and behavior of the background management interface, such as defining the fields to be displayed, search and filter options, sorting rules, and so on.

11- Restart the web service and display the effect

CTRL+C ends the previously started web service, then restarts:

CD E:\Python_project\P_001\myshop-test\good_info\
E:
python manage.py runserver

Access background management:
http://127.0.0.1:8000/admin/username
(administrator) and password (bb123456)
insert image description here
insert image description here
record the above screenshot as "Home image" and
click "Product Information" in "Home image", The interface is as follows:
insert image description here
Click "Product Classification" in the "Home Map", the interface is as follows:
insert image description here
Click "+ Add" on the right side of "Product Information" in the "Home Map", the interface is as follows:
insert image description here
Click "Product Classification" in the "Home Map" "+ Add" on the right, the interface is as follows:
insert image description here

12- Write data test

12-1-Create a piece of "commodity classification" data

insert image description here
insert image description here
insert image description here

12-2-Create a piece of "commodity information" data

insert image description here
insert image description here
insert image description here

13-The download link of the compressed package of the entire Project

The download link of the compressed package of the entire Project:
https://pan.baidu.com/s/1DwfwH79cE6SB67hZqa-Q3w?pwd=hyrd

Guess you like

Origin blog.csdn.net/wenhao_ir/article/details/131856663