[Django web development] 05. Database operation, actual user management (nanny level graphics)

Table of Contents

  • 1. Install third-party modules
  • 2. ORM
    • 2.1 Create the database manually by yourself
    • 2.2 django connection database
    • 2.3 Where is the table creation statement written?
    • 2.4 How to run and take effect after the table creation statement is written?
  • 3. Operation table
    • 3.1 Create a data table
    • 3.2 Modify the data table
  • 4. Manipulating data
    • 4.1 Insert data
    • 4.2 Delete data
    • 4.3 Modify data
    • 4.4 Query data
  • 5. Actual combat: user management
    • 5.1 User display
    • 5.2 User Addition
    • 5.3 User deletion
    • Summarize

Welcome to the “Django Web Development” series, which is being updated continuously
Welcome to the “Django Web Development” series, which is being updated continuously

1. Install third-party modules

pip install mysqlclient


2. ORM

ORM features:

  • Create, modify, and delete tables in the database (without you writing SQL statements). [Unable to create database]

  • Operate the data in the table (without writing SQL statements).

To put it simply, ORM can be understood as Mandarin, SQL statements are dialects, and ORM is a translation of SQL statements. The main disadvantage is that it cannot create a database. The advantage is that it is simple and efficient to write. (operating efficiency is not guaranteed)

2.1 Create the database manually

  • Start the MySQL service

  • Self-contained tool to create database

    • Created using the command line
      first mysql login
      Then enter the command
create database database name DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
create database day15 DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
  • Use tools such as navicat to create (note the creation of database character set arrangement rules)

2.2 django connection database

Modify the database configuration DATABASES in the project’s setting.py

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

DATABASES = {<!-- -->
    'default': {<!-- -->
        'ENGINE': 'django.db.backends.mysql', # driver
        'NAME': 'day15', # database name
        'USER': 'root', # mysql username
        'PASSWORD': '123456', # mysql password
        'HOST': '127.0.0.1', # MySQL is installed locally
        'PORT': 3306, # port
    }
}

2.3 Where is the table creation statement written?

All operations need to write the ORM statement in the moudle.py in the registered app, as shown in the figure below app01 is already registered, write the moudle.py in it

2.4 How to run and take effect after the table creation statement is written?

In the project root directory (there is a manage.py file in the root directory, in the outermost layer), cmd executes the code below, and executes the moudle.py files of each app from top to bottom according to the order of registered apps.

python manage.py makemigrations
python manage.py migrate
  • makemigrations description:
  • Record all our changes to models.py, and migrate this change to the migrations file to generate a file, which is equivalent to a buffer change, but it will not really affect our database at this time.
  • Area of application: all apps
python manage.py makemigrations

After successful execution, the contents of the folder appear:

  • migrate Description:
  • These changes affect the database, that is, execute the newly changed migration file in migrations to update the database, such as creating a data table, or adding field attributes
  • Area of application: all apps
python manage.py migrate
  • If you want to only work on some apps, execute the following command:
python manage.py makemigrations appname
python manage.py migrate appname
  • If you want to be precise to a certain migration file, you can use:
python manage.py migrate appname filename

3. Action sheet

Note that our app registration list has many official default apps by default, so many official built-in tables will be generated when we operate the database for the first time. We only need to pay attention to the newly created tables when we study.

3.1 Create a data table

  • moudle.py content
from django.db import models

class UserInfo(models.Model):#A class is a table
    name = models. CharField(max_length=32)
    password = models.CharField(max_length=64)
# The UserInfo code above is equivalent to the code below
# CREATE TABLE `app01_userinfo` (
# `id` bigint NOT NULL AUTO_INCREMENT,
# `name` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
# `password` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
# PRIMARY KEY (`id`) USING BTREE
# )


Observe the newly created table, and add an id primary key to us by default

3.2 Modify data table

When adding a new column in a table, since there may already be data in the existing column, the new column must specify the data corresponding to the new column:

  • 1. Enter a value manually.

  • set default

    age = models. IntegerField(default=2)
    
  • Allow empty

    data = models. IntegerField(null=True, blank=True)
    
  • moudle.py content

from django.db import models

class UserInfo(models.Model):#A class is a table
    name = models. CharField(max_length=32)
    password = models.CharField(max_length=64)
    age = models.IntegerField(default=2)#Add this column
# The UserInfo code above is equivalent to the code below
# CREATE TABLE `app01_userinfo` (
# `id` bigint NOT NULL AUTO_INCREMENT,
# `name` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
# `password` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
# `age` int NOT NULL,
# PRIMARY KEY (`id`) USING BTREE
# )


4. Operation data

4.1 Insert data

Create a new department table first, and then insert data, otherwise an error will be reported that the department table does not exist. This step needs to be operated twice separately.

  • moudle.py content
from django.db import models


class UserInfo(models.Model):#A class is a table
    name = models. CharField(max_length=32)
    password = models.CharField(max_length=64)
    age = models.IntegerField(default=2)#Add this column

class Department(models.Model):# Create a new department class
    title = models.CharField(max_length=16)#Department name

– After executing the cmd command to create a table

  • moudle.py content
from django.db import models


class UserInfo(models.Model):#A class is a table
    name = models. CharField(max_length=32)
    password = models.CharField(max_length=64)
    age = models.IntegerField(default=2)#Add this column

class Department(models.Model):# Create a new department class
    title = models.CharField(max_length=16)#Department name

# #### 1. Insert data ####
Department.objects.create(title="Sales Department")
Department.objects.create(title="IT Department")
Department.objects.create(title="Operation Department")
UserInfo.objects.create(name="Wu Peiqi", password="123", age=19)
UserInfo.objects.create(name="Zhu Hufei", password="666", age=29)
UserInfo.objects.create(name="Wu Yangjun", password="666")

4.2 Delete data

In general, it is recommended to create a new orm webpage for quick testing, avoiding the cumbersome use of the command line, so that you only need to open the orm to execute the statement


Note here that data cannot be deleted in moudle.py, and an error django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. will be reported and the reason is unknown.

  • view.py content
from app01.models import Department, UserInfo
def orm(request):
    # #### 2. Delete ####
    UserInfo.objects.filter(id=3).delete()
    Department.objects.all().delete()
    
    return HttpResponse("Success")

4.3 Modify data

  • moudle.py core content
# #### 3. Modify data ####
UserInfo.objects.all().update(password=999)#Change everyone's password to 999
UserInfo.objects.filter(id=2).update(age=999)#Change the age of the record with id 2 to 999
UserInfo.objects.filter(name="Zhu Hufei").update(age=999)#Change the age of the record whose name is Zhu Hufei to 999

4.4 Query data

  • moudle.py content
from django.db import models


class UserInfo(models.Model):#A class is a table
    name = models. CharField(max_length=32)
    password = models.CharField(max_length=64)
    age = models.IntegerField(default=2)#Add this column

class Department(models.Model):# Create a new department class
    title = models.CharField(max_length=16)#Department name

# #### 4. Query data ####
# 4.1 Get all the data that meets the conditions
# data_list = [object, object, object] QuerySet type
data_list = UserInfo.objects.all()#A list of data
print("traversal print all")
for obj in data_list:#
    print(obj.id, obj.name, obj.password, obj.age)

#data_list = [object,]
data_list = UserInfo.objects.filter(id=1)
print(data_list)#print the first item
#4.2 Get the first piece of data [object]
row_obj = UserInfo.objects.filter(id=1).first()
print("Print each column data of row_obj")
print(row_obj.id, row_obj.name, row_obj.password, row_obj.age)


5. Actual combat: user management

url.py add url

 # Case: user management
    path('info/list/', views.info_list), #display user list

    path('info/add/', views.info_add), #add user

    path('info/delete/', views.info_delete), #delete user

5.1 User display

  • view.py gets data and returns data_list
def info_list(request):
    # 1. Get all user information in the database
    # [object, object, object]
    data_list = UserInfo.objects.all()

    # 2. Render and return to the user
    return render(request, "info_list.html", {<!-- -->"data_list": data_list})
  • info_list.html content
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>INFO list</h1>


<table border="1">
    <thead>
    <tr>
        <th>ID</th>
        <th>Name</th>
        <th>Password</th>
        <th>age</th>
        <th>Operation</th>
    </tr>
    </thead>
    <tbody>
    {% for obj in data_list %}
        <tr>
            <td>{<!-- -->{ obj.id }}</td>
            <td>{<!-- -->{ obj.name }}</td>
            <td>{<!-- -->{ obj.password }}</td>
            <td>{<!-- -->{ obj. age }}</td>
        </tr>
    {% endfor %}
    </tbody>
</table>


</body>
</html>

5.2 User addition

Modify the original user display list and add an add user button Add to jump to the user addition page

  • info_list.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>INFO list</h1>

<a href="/info/add/">Add</a>

<table border="1">
    <thead>
    <tr>
        <th>ID</th>
        <th>Name</th>
        <th>Password</th>
        <th>age</th>
        <th>Operation</th>
    </tr>
    </thead>
    <tbody>
    {% for obj in data_list %}
        <tr>
            <td>{<!-- -->{ obj.id }}</td>
            <td>{<!-- -->{ obj.name }}</td>
            <td>{<!-- -->{ obj.password }}</td>
            <td>{<!-- -->{ obj. age }}</td>
        </tr>
    {% endfor %}
    </tbody>
</table>


</body>
</html>

  • view.py gets the value from the form, writes it to the database and jumps back to the user display list
def info_add(request):
    if request.method == "GET":
        return render(request, 'info_add.html')

    # Get the data submitted by the user
    user = request. POST. get("user")
    pwd = request.POST.get("pwd")
    age = request.POST.get("age")

    # add to database
    UserInfo.objects.create(name=user, password=pwd, age=age)

    # auto jump
    # return redirect("http://127.0.0.1:8000/info/list/")
    return redirect("/info/list/")#Simplification of the previous line of writing
  • info_add.html content
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>Add user</h1>
<form method="post">
    {% csrf_token %} {# Be careful not to forget csrf! ! ! #}
    <input type="text" name="user" placeholder="username">
    <input type="text" name="pwd" placeholder="password">
    <input type="text" name="age" placeholder="age">
    <input type="submit" value="submit">
</form>


</body>
</html>

5.3 User deletion

Modify the original user display list and add an add user button delete to delete a user

  • info_list.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>INFO list</h1>

<a href="/info/add/">Add</a>

<table border="1">
    <thead>
    <tr>
        <th>ID</th>
        <th>Name</th>
        <th>Password</th>
        <th>age</th>
        <th>Operation</th>
    </tr>
    </thead>
    <tbody>
    {% for obj in data_list %}
        <tr>
            <td>{<!-- -->{ obj.id }}</td>
            <td>{<!-- -->{ obj.name }}</td>
            <td>{<!-- -->{ obj.password }}</td>
            <td>{<!-- -->{ obj.age }}</td>
            <td>
                <a href="/info/delete/?nid={<!-- -->{ obj.id }}">Delete</a>
            </td>
        </tr>
    {% endfor %}
    </tbody>
</table>


</body>
</html>

  • view.py
# http://127.0.0.1:8000/info/delete/?nid=1
# http://127.0.0.1:8000/info/delete/?nid=2
# http://127.0.0.1:8000/info/delete/?nid=3
def info_delete(request):
    nid = request.GET.get('nid')#Get the id from get
    UserInfo.objects.filter(id=nid).delete()#Delete according to the specified id
    return redirect("/info/list/")#Jump back to the user list page

Summary

If you like it, give it a , click a follow! Share more interesting and fun Python web development knowledge with you!

Copyright Notice:

Found that you have gone far @mzh original works, reprints must mark the original text link

Copyright 2023 mzh

Crated: 2023-3-1

Welcome to the “Django Web Development” series, which is being updated continuously
Welcome to the “Django Web Development” series, which is being updated continuously
“01. Install and configure Django”
“02. Create and run a Django project”
『03. Getting to know Django for the first time』
“04. Request and response, web page jump redirection, simple form simulation login in actual combat”
“05. Database operation, actual user management”
『06. Error: You have 26 unapplied migration(s). Your project may not work properly until you apply the migra』
“07. Template syntax”
“08. Practical Project: Department and Employee Management System (01)”
『09. Practical project: employee editing and deletion function and management of pretty numbers (02)』
“10. Practical project: search function of good numbers (03)”
“11. Practical project: pagination and page number jump function (04)”
“12. Practical project: Encapsulation of paging components, interface-oriented programming (05)”
“13. Practical project: time selection component when adding users (06)”
“14. Practical project: some object-oriented code structure optimization (07)”
“15. Practical projects: Additions, deletions, modifications and checks by administrators, md5 passwords and password resets (08)”
“16. Actual project: further optimization of BootStrap class (09)”
“17. Practical project: login business involves cookies, sessions, and middleware (10)”
“18. Practical project: Verification code when logging in (11)”
『19. Practical Project: Getting to Know Ajax Requests (12)』
“20. Practical Project: Ajax Practical Order Management and Pop-up Dialog Box (13)”
“21. Practical project: echart data chart (14)”
“22. Practical project: simple file upload (15)”
“23. Practical project: Excel, form and moudleForm file upload (16)”
【Stay tuned for more content】