Response requests and database operations in Django projects

    • request and response

  • views.py

def something(request):
    # request是一个对象,封装了用户发送过来的所有请求相关数据
    # 获取请求方式
    print(request.method)
    # 在url上传递一些值 http://127.0.0.1:8000/something/?n1=123&n2=999
    print(request.GET)
    # 在请求体中提交数据
    print(request.POST)
    # 【响应】字符串内容返回给请求者
    # return HttpResponse("返回内容")
    # 【响应】读取html中的内容+渲染(替换)-> 字符串,返回给用户
    # return render(request, "something.html")
    # 【响应】让浏览器重定向到其他的页面
    return redirect("https://www.baidu.com")

Case: login

  • view.py

def login(request):
    if request.method == "GET":
        return render(request, "login.html")
    # 如果是POST请求,救护去用户提交的数据
    print(request.POST)
    username = request.POST.get("user")
    password = request.POST.get("pwd")
    if username == 'root' and password == '123':
        # return HttpResponse("登陆成功")
        return redirect("https://www.baidu.com")
    # return HttpResponse("登陆失败")
    return render(request, "login.html", {"error_msg": "用户名或密码错误"})
  • login.html: Be sure to add {% csrf_token %} to the form

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>用户登录</h1>
<form method="post" action="/login/">
    {% csrf_token %}
    <input type="text" name="user" placeholder="用户名">
    <input type="password" name="pwd" placeholder="密码">
    <input type="submit" value="提 交">
    <span style="color:red">{
    
    { error_msg }}</span>
</form>
</body>
</html>

2. Operate the database

  • Django can develop and operate the database more easily, and an ORM framework is provided internally.

2.1 Install third-party modules

conda install mysqlclient

2.2ORM

  • ORM can help us do two things:

  • Create, modify and drop tables in the database. (No need to write SQL statement) [Unable to create database]

  • Manipulate the data in the table. (No need to write SQL statement)

1. Create your own database

mysql -u root -p
create database db1;
show database;

2. Django connects to the database

  • Configure in the setting.py file. Comment out the original database configuration. Refer to the official documentation

# DATABASES = {
#     'default': {
#         'ENGINE': 'django.db.backends.sqlite3',
#         'NAME': BASE_DIR / 'db.sqlite3',
#     }
# }

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'db1',
        'USER': 'root',
        'PASSWORD': '12345678',
        "HOST": 'localhost',
        'PORT': '3306',
    }
}

3. Django action sheet

create table

  • model.py

from django.db import models


# Create your models here.
class UserInfo(models.Model):
    name = models.CharField(max_length=32)
    password = models.CharField(max_length=64)
    age = models.IntegerField()

  • It is equivalent to entering the following command in the terminal:

create table app01_userinfo(
    id bigint auto_increment primary key,
    name varchar(32),
    password varchar(64),
    age int
);
  • Execute the command in the terminal (in the directory where the manage.py file is located)

python manage.py makemigrations
python manage.py migrate

Note: the app needs to be registered

  • Execute in terminal

use db1;
mysql> show tables;
+----------------------------+
| Tables_in_db1              |
+----------------------------+
| app01_userinfo             |
| auth_group                 |
| auth_group_permissions     |
| auth_permission            |
| auth_user                  |
| auth_user_groups           |
| auth_user_user_permissions |
| django_admin_log           |
| django_content_type        |
| django_migrations          |
| django_session             |
+----------------------------+
11 rows in set (0.00 sec)

mysql> desc app01_userinfo;
+----------+-------------+------+-----+---------+----------------+
| Field    | Type        | Null | Key | Default | Extra          |
+----------+-------------+------+-----+---------+----------------+
| id       | bigint      | NO   | PRI | NULL    | auto_increment |
| name     | varchar(32) | NO   |     | NULL    |                |
| password | varchar(64) | NO   |     | NULL    |                |
| age      | int         | NO   |     | NULL    |                |
+----------+-------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
  • You will find that many tables are automatically created, and the app01_userinfo we need is created

modify or drop a table

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

  • 1. Manually enter a value

  • 2. Set default value or allow empty

age = models.IntegerField(default=2)
data = models.IntegerField(null=True, blank=True)
  • In the future, if you want to adjust the table structure during development, you only need to operate in the models.py file. Then enter the command in the terminal

python manage.py makemigrations
python manage.py migrate

4. Operational data - adding, deleting, modifying and checking

  • view.py

from app01 import models


def orm(request):
    # 测试ORM操作表中的数据
    # ### 1.新建 ###
    # models.Department.objects.create(title='销售部')
    # models.Department.objects.create(title='IT部')
    # models.Department.objects.create(title='运营部')
    # models.UserInfo.objects.create(name='qy', password='123', age=20)
    # models.UserInfo.objects.create(name='qy1', password='123', age=21)
    # ### 2.删除数据 ###
    # models.UserInfo.objects.filter(id=2).delete()
    # models.Department.objects.all().delete()
    # ### 3.获取数据 ###
    # 3.1获取符合条件的所有数据
    # data_list伪QuerySet类型
    # data_list = models.UserInfo.objects.all()
    # for obj in data_list:
    #     print(obj.id, obj.name, obj.age)
    # 3.2获取符合条件的第一条数据
    # row_obj = models.UserInfo.objects.filter(id=1).first()
    # print(row_obj.id, row_obj.name, row_obj.age)
    # ### 4.更新数据 ###
    # models.UserInfo.objects.update(password=999)
    models.UserInfo.objects.field(id=1).update(passwoed=111)
    return HttpResponse("创建成功")

Case: User Management

1. Display user list /info/list

  • url.py

  • views.py

  • Get all user information

  • HTML rendering

2. Add user/info/add

  • url.py

  • view.py

  • GET, see page, enter content

  • POST, submit content, write to the database

3. Delete user/info/delete

  • url.py

  • view.py

  • On the /info/list interface, add a delete button to delete users with a solid line

Guess you like

Origin blog.csdn.net/qyqyqyi/article/details/128832304