14 数据的查询,新增,删除,编辑(针对用户表增删改查)

需求:

1.查看当前所有表数据(前端展示)  /home/
2.书写用户注册页面(前端展示)   /register/
3.编辑用户数据
4.删除用户

前期准备

 

 

settings.py

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    # 'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME':"db123",
        "HOST":'127.0.0.1',
        "PORT":3306,
        "USER":'root',
        "PASSWORD":'123',
        "CHARSET":"utf8"
    }
}

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR,'static')
]

 

models.py

from django.db import models

# Create your models here.

class User(models.Model):
    id = models.AutoField(verbose_name="编号",primary_key=True)
    name = models.CharField(verbose_name="姓名",max_length=32)
    password = models.IntegerField(verbose_name="密码")

    def __str__(self):
        return self.name     #添加打印功能,显示具体的对象

 

urls:


from django.shortcuts import render,HttpResponse,redirect
from app01 import models

# Create your views here.
def home(request):
# 1.查询user表中所有的数据
user_data = models.User.objects.all() # queryset [数据对象,数据对象,数据对象]
# 2.将数据利用模板语法传递给html文件
return render(request,'home.html',locals()) # {'user_data':user_data}


def register(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
# 先比对用户名是否重复
is_exists = models.User.objects.filter(name=username) # queryset[]
if is_exists:
return HttpResponse("用户名已存在")
# 将用户数据写入数据库
models.User.objects.create(name=username,password=password)
# 返回数据展示
return redirect('/home/')
return render(request,'register.html')


def data_delete(request):
# 获取用户需要删除的数据主键值
delete_id = request.GET.get('delete_id')
# 利用orm删除即可
models.User.objects.filter(id=delete_id).delete()
# 再次返回数据展示页
return redirect('/home/')


def data_edit(request):
# 1.获取用户需要修改的数据主键值
edit_id = request.GET.get('edit_id')

if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
# 修改表数据
models.User.objects.filter(id=edit_id).update(name=username,password=password)
# 返回展示页
return redirect('/home/')

# 2.根据主键值查询具体数据
edit_obj = models.User.objects.filter(id=edit_id).first() # queryset[数据对象]
'''filter的结果是一个queryset可以看成是列表套数据对象 在取值的时候可以用索引 但是推荐使用first方法'''
# 3.返回给用户一个编辑页面 上面提前写好了用户需要编辑的数据
return render(request,'edit_data.html',locals())
 

home.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    {% load static %}
    <link rel="stylesheet" href="{% static 'bootstrap-3.4.1-dist/css/bootstrap.min.css' %}">
</head>
<body>
<div class="container">
    <div class="row">
        <h1 class="text-center">数据展示</h1>

        <div class="col-md-8 col-md-offset-2">
        <a href="/register" class="btn btn-primary">用户注册</a>
            <table class="table table-striped table-hover">
                <thead>
                    <tr>
                        <th>id</th>
                        <th>name</th>
                        <th>password</th>
                        <th>others</th>

                    </tr>
                </thead>
                <tbody>
                   {% for user_obj in user_data %}
                       <tr>
                            <td>{{ user_obj.id }}</td>
                            <td>{{ user_obj.name }}</td>
                            <td>{{ user_obj.password }}</td>
                            <td>
                                 <a href="/data_edit/?edit_id={{ user_obj.id }}" class="btn btn-primary btn-xs">编辑</a>
                                 <a href="/data_delete/?delete_id={{ user_obj.id }}" class="'btn btn-danger btn-xs">删除</a>
                            </td>


                    </tr>

                   {% endfor %}


                </tbody>
            </table>

        </div>
    </div>

</div>

</body>
</html>

register.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
      {% load static %}
    <link rel="stylesheet" href="{% static 'bootstrap-3.4.1-dist/css/bootstrap.min.css' %}">
</head>
<body>
    <div class="container">

        <div class="row">
            <h1 class="text-center">用户注册</h1>
            <div class="col-md-8 col-md-offset-2">
                <form action="" method="POST" >
                     <p>username:
                    <input type="text" name="username" class="form-control">

                </p>
                <p>password:
                    <input type="password" name="password" class="form-control">

                </p>
                    <input type="submit" values="注册" class="btn btn-danger btn-block">
                </form>

            </div>
        </div>
    </div>

</body>
</html>

edit_data.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
      {% load static %}
    <link rel="stylesheet" href="{% static 'bootstrap-3.4.1-dist/css/bootstrap.min.css' %}">
</head>
<body>
    <div class="container">

        <div class="row">
            <h1 class="text-center">编辑用户</h1>
            <div class="col-md-8 col-md-offset-2">
                <form action="" method="POST" >
                     <p>username:
                    <input type="text" name="username" class="form-control" value="{{ edit_obj.name }}">

                </p>
                <p>password:
                    <input type="text" name="password" class="form-control" value="{{ edit_obj.password }}">

                </p>
                    <input type="submit" values="编辑" class="btn btn-success btn-block">
                </form>

            </div>
        </div>
    </div>

</body>
</html>

 

 

posted @ 2021-11-23 23:57  甜甜de微笑  阅读(202)  评论(0编辑  收藏  举报