django项目实战一(django+bootstrap实现增删改查)

news2024/12/25 12:38:59

目录

一、创建django项目

二、修改默认配置

三、配置数据库连接

四、创建表结构

五、在app当中创建静态文件

六、页面实战-部门管理

1、实现一个部门列表页面

2、实现新增部门页面

3、实现删除部门

4、实现部门编辑功能

七、模版的继承

1、创建模板layout.html

1)将公共的部分写进模版

2)后续新的html页面使用下面方法继承模版

2、将depart_list.html页面使用模版重构

3、将depart_add.html页面重构

4、将depart_edit.html页面重构

八、页面实战-用户管理

1、uri注册

2、views.py

3、用户列表页面

4、添加用户user_add.html--- 老方法

5、添加用户user_model_form_add.html--- 新方法(ModelForm)

6、解决提示英文问题

 7、编辑用户 -新增user_edit.html页面

8、编辑用户 -修改views.py

9、修改数据库入职时间为年月日格式

10、删除用户在views.py新增user_delete方法


一、创建django项目

使用pycharm创建django项目

二、修改默认配置

1、删除settings配置

删除下图[]内容

 2、删除templates文件夹

三、创建app(应用)与注册应用

1、创建app

# XXX项目名
python manage.py startapp xxx

2、注册app

修改settings如下图,红色方框是创建的app名

三、配置数据库连接

1、安装pymysql

pip install pymysql

 2、配置在项目同名包下的_init_.py里面添加

import pymysql
pymysql.install_as_MySQLdb()

3、修改settings.py

,注释db.sqlite3的配置新增下图

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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',  # 数据库的类型
        'NAME': 'texx',  # 所使用的的数据库的名字
        'USER': 'root',  # 数据库服务器的用户
        'PASSWORD': 'xxxx',  # 密码
        'HOST': '127.0.0.1',  # 主机
        'PORT': '3306',  # 端口
    }
}

四、创建表结构

 1、在models.py创建类

from django.db import models

# Create your models here.


class Department(models.Model):
    """部门表"""
    name = models.CharField(verbose_name='部门名称', max_length=20)


class UserInfo(models.Model):
    """员工表"""
    name = models.CharField(verbose_name='姓名', max_length=20)
    password = models.CharField(verbose_name='密码', max_length=64)
    age = models.IntegerField(verbose_name='年龄')
    gender_choices = ((1, '男'), (2, '女'))
    gender = models.SmallIntegerField(verbose_name='性别',choices=gender_choices)
    account = models.DecimalField(verbose_name='账户余额', max_digits=10, decimal_places=2,default=0)
    create_time = models.DateTimeField(verbose_name='入职时间')
    # depart会自动生成字段为depart_id
    # 级联删除 on_delete=models.CASCADE
    # 置空 on_delete=models.SET_NULL 但是必须和null=True, blank=True配合使用,因为你得支持为null
    depart = models.ForeignKey(to='Department', to_field='id', on_delete=models.CASCADE)

2、创建一个mysql数据库(略)

3、django命令生成库表

python manage.py makemigrations 
python manage.py migrate

另一个方法:按下图操作之后就可省略上图 python manage.py 命令直接输入后面的即可

五、在app当中创建静态文件

1、创建下图目录

 2、将下载的bootstrap-3.4.1复制到plugins

3、将下载的jquery-3.6.3.min.js复制到js

 4、在app应用下创建templates文件夹

六、页面实战-部门管理

1、实现一个部门列表页面

1)设置部门列表路由

from django.contrib import admin
from django.urls import path
from TestManagementSystem import views

urlpatterns = [
    # path('admin/', admin.site.urls),
    path('depart/list/', views.depart_list),
]

2)创建部门列表views.py视图

from django.shortcuts import render
from TestManagementSystem import models
# Create your views here.


def depart_list(request):
    """部门列表"""
    # 查询所有部门
    depart_set = models.Department.objects.all()
    print(depart_set)
    return render(request, 'depart_list.html', {"depart_set": depart_set})

3)创建部门列表html页面

在templates下创建depart_list.html

先引入样式、js等

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>部门列表</title>
    <link rel="stylesheet" href="{% static 'plugins/bootstrap-3.4.1/css/bootstrap.min.css' %}">
</head>
<body>

    <script src="{% static 'js/jquery-3.6.3.min.js'%}"></script>
    <script src="{% static 'plugins/bootstrap-3.4.1/js/bootstrap.js'%}"></script>
</body>
</html>

加入导航

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>部门列表</title>
    <link rel="stylesheet" href="{% static 'plugins/bootstrap-3.4.1/css/bootstrap.min.css' %}"/>

</head>
<body>


<nav class="navbar navbar-default">
  <div class="container-fluid">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="#">测试管理系统</a>
    </div>
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav">
        <li><a href="/depart/list/">部门管理</a></li>
        <li><a href="#">Link</a></li>
      </ul>

      <ul class="nav navbar-nav navbar-right">
        <li><a href="#">登录</a></li>
        <li class="dropdown">
          <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">春天的菠菜 <span class="caret"></span></a>
          <ul class="dropdown-menu">
            <li><a href="#">个人资料</a></li>
            <li><a href="#">我的信息</a></li>
            <li role="separator" class="divider"></li>
            <li><a href="#">注销</a></li>
          </ul>
        </li>
      </ul>
    </div>
  </div>
</nav>

    <script src="{% static 'js/jquery-3.6.3.min.js'%}"></script>
    <script src="{% static 'plugins/bootstrap-3.4.1/js/bootstrap.js'%}"></script>
</body>
</html>

完成动态数据

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>部门列表</title>
    <link rel="stylesheet" href="{% static 'plugins/bootstrap-3.4.1/css/bootstrap.min.css' %}"/>

</head>
<body>


<nav class="navbar navbar-default">
    <div class="container">  <!-- <div class="container-fluid">  -->
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
                    data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">测试管理系统</a>
        </div>
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav">
                <li><a href="/depart/list/">部门管理</a></li>
                <li><a href="#">Link</a></li>
            </ul>

            <ul class="nav navbar-nav navbar-right">
                <li><a href="#">登录</a></li>
                <li class="dropdown">
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true"
                       aria-expanded="false">春天的菠菜 <span class="caret"></span></a>
                    <ul class="dropdown-menu">
                        <li><a href="#">个人资料</a></li>
                        <li><a href="#">我的信息</a></li>
                        <li role="separator" class="divider"></li>
                        <li><a href="#">注销</a></li>
                    </ul>
                </li>
            </ul>
        </div>
    </div>
</nav>

<div>
    <div class="container">
        <div style="margin-bottom: 10px">
            <a class="btn btn-success" href="#">
                <span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span>
                新建
            </a>
        </div>

        <div class="bs-example" data-example-id="panel-without-body-with-table">
            <div class="panel panel-default">
                <!-- Default panel contents -->
                <div class="panel-heading">
                    <span class="glyphicon glyphicon-th-list" aria-hidden="true"></span>
                    部门列表
                </div>

                <!-- Table -->
                <table class="table table-bordered">
                    <thead>
                    <tr>
                        <th>序号</th>
                        <th>名称</th>
                        <th>操作</th>

                    </tr>
                    </thead>
                    <tbody>
                    {% for obj in depart_set %}
                        <tr>
                            <th scope="row">{{ obj.id }}</th>
                            <td>{{ obj.name }}</td>
                            <td>
                                <a class="btn btn-primary btn-xs">编辑</a>
                                <a class="btn btn-danger btn-xs">删除</a>
                            </td>
                        </tr>
                    {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>


    </div>
</div>


<script src="{% static 'js/jquery-3.6.3.min.js' %}"></script>
<script src="{% static 'plugins/bootstrap-3.4.1/js/bootstrap.js' %}"></script>
</body>
</html>

 数据从数据库里做几个,后续新增就可以实现页面新增

2、实现新增部门页面

url注册

"""DjangoDemoOne URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from TestManagementSystem import views

urlpatterns = [
    # path('admin/', admin.site.urls),
    path('depart/list/', views.depart_list),
    path('depart/add/', views.depart_add),
]

新增depart_add.html页面

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>部门列表</title>
    <link rel="stylesheet" href="{% static 'plugins/bootstrap-3.4.1/css/bootstrap.min.css' %}"/>

</head>
<body>


<nav class="navbar navbar-default">
    <div class="container">  <!-- <div class="container-fluid">  -->
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
                    data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">测试管理系统</a>
        </div>
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav">
                <li><a href="/depart/list/">部门管理</a></li>
                <li><a href="#">Link</a></li>
            </ul>

            <ul class="nav navbar-nav navbar-right">
                <li><a href="#">登录</a></li>
                <li class="dropdown">
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true"
                       aria-expanded="false">春天的菠菜 <span class="caret"></span></a>
                    <ul class="dropdown-menu">
                        <li><a href="#">个人资料</a></li>
                        <li><a href="#">我的信息</a></li>
                        <li role="separator" class="divider"></li>
                        <li><a href="#">注销</a></li>
                    </ul>
                </li>
            </ul>
        </div>
    </div>
</nav>

<div>
    <div class="container">
        <div style="margin-bottom: 10px">
            <a class="btn btn-success" href="/depart/add/">
                <span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span>
                新建
            </a>
        </div>

        <div class="bs-example" data-example-id="panel-without-body-with-table">
            <div class="panel panel-default">
                <!-- Default panel contents -->
                <div class="panel-heading">
                    <span class="glyphicon glyphicon-th-list" aria-hidden="true"></span>
                    部门列表
                </div>

                <!-- Table -->
                <table class="table table-bordered">
                    <thead>
                    <tr>
                        <th>序号</th>
                        <th>名称</th>
                        <th>操作</th>

                    </tr>
                    </thead>
                    <tbody>
                    {% for obj in depart_set %}
                        <tr>
                            <th scope="row">{{ obj.id }}</th>
                            <td>{{ obj.name }}</td>
                            <td>
                                <a class="btn btn-primary btn-xs">编辑</a>
                                <a class="btn btn-danger btn-xs">删除</a>
                            </td>
                        </tr>
                    {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>


    </div>
</div>


<script src="{% static 'js/jquery-3.6.3.min.js' %}"></script>
<script src="{% static 'plugins/bootstrap-3.4.1/js/bootstrap.js' %}"></script>
</body>
</html>

depart_list新增链接到depart_add页面

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>部门列表</title>
    <link rel="stylesheet" href="{% static 'plugins/bootstrap-3.4.1/css/bootstrap.min.css' %}"/>

</head>
<body>


<nav class="navbar navbar-default">
    <div class="container">  <!-- <div class="container-fluid">  -->
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
                    data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">测试管理系统</a>
        </div>
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav">
                <li><a href="/depart/list/">部门管理</a></li>
                <li><a href="#">Link</a></li>
            </ul>

            <ul class="nav navbar-nav navbar-right">
                <li><a href="#">登录</a></li>
                <li class="dropdown">
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true"
                       aria-expanded="false">春天的菠菜 <span class="caret"></span></a>
                    <ul class="dropdown-menu">
                        <li><a href="#">个人资料</a></li>
                        <li><a href="#">我的信息</a></li>
                        <li role="separator" class="divider"></li>
                        <li><a href="#">注销</a></li>
                    </ul>
                </li>
            </ul>
        </div>
    </div>
</nav>

<div>
    <div class="container">
        <div style="margin-bottom: 10px">
            <a class="btn btn-success" href="/depart/add/">
                <span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span>
                新建
            </a>
        </div>

        <div class="bs-example" data-example-id="panel-without-body-with-table">
            <div class="panel panel-default">
                <!-- Default panel contents -->
                <div class="panel-heading">
                    <span class="glyphicon glyphicon-th-list" aria-hidden="true"></span>
                    部门列表
                </div>

                <!-- Table -->
                <table class="table table-bordered">
                    <thead>
                    <tr>
                        <th>序号</th>
                        <th>名称</th>
                        <th>操作</th>

                    </tr>
                    </thead>
                    <tbody>
                    {% for obj in depart_set %}
                        <tr>
                            <th scope="row">{{ obj.id }}</th>
                            <td>{{ obj.name }}</td>
                            <td>
                                <a class="btn btn-primary btn-xs">编辑</a>
                                <a class="btn btn-danger btn-xs">删除</a>
                            </td>
                        </tr>
                    {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>


    </div>
</div>


<script src="{% static 'js/jquery-3.6.3.min.js' %}"></script>
<script src="{% static 'plugins/bootstrap-3.4.1/js/bootstrap.js' %}"></script>
</body>
</html>

views新增depart_add方法

from django.shortcuts import render, redirect, HttpResponse
from TestManagementSystem import models
# Create your views here.


def depart_list(request):
    """部门列表"""
    # 查询所有部门
    depart_set = models.Department.objects.all()
    return render(request, 'depart_list.html', {"depart_set": depart_set})


def depart_add(request):
    """新增部门"""
    # 新增部门    
    # return HttpResponse("成功")
    if request.method =='GET':
        return render(request, 'depart_add.html')
    depart_name = request.POST.get("departname")
    models.Department.objects.create(name=depart_name)
    return redirect('/depart/list')

3、实现删除部门

url注册

"""DjangoDemoOne URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from TestManagementSystem import views

urlpatterns = [
    # path('admin/', admin.site.urls),
    path('depart/list/', views.depart_list),
    path('depart/add/', views.depart_add),
    path('depart/delete/', views.depart_delete),
]

修改depart_list页面的,修改删除按钮业务

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>部门列表</title>
    <link rel="stylesheet" href="{% static 'plugins/bootstrap-3.4.1/css/bootstrap.min.css' %}"/>

</head>
<body>


<nav class="navbar navbar-default">
    <div class="container">  <!-- <div class="container-fluid">  -->
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
                    data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">测试管理系统</a>
        </div>
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav">
                <li><a href="/depart/list/">部门管理</a></li>
                <li><a href="#">Link</a></li>
            </ul>

            <ul class="nav navbar-nav navbar-right">
                <li><a href="#">登录</a></li>
                <li class="dropdown">
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true"
                       aria-expanded="false">春天的菠菜 <span class="caret"></span></a>
                    <ul class="dropdown-menu">
                        <li><a href="#">个人资料</a></li>
                        <li><a href="#">我的信息</a></li>
                        <li role="separator" class="divider"></li>
                        <li><a href="#">注销</a></li>
                    </ul>
                </li>
            </ul>
        </div>
    </div>
</nav>

<div>
    <div class="container">
        <div style="margin-bottom: 10px">
            <a class="btn btn-success" href="/depart/add/">
                <span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span>
                新建
            </a>
        </div>

        <div class="bs-example" data-example-id="panel-without-body-with-table">
            <div class="panel panel-default">
                <!-- Default panel contents -->
                <div class="panel-heading">
                    <span class="glyphicon glyphicon-th-list" aria-hidden="true"></span>
                    部门列表
                </div>

                <!-- Table -->
                <table class="table table-bordered">
                    <thead>
                    <tr>
                        <th>序号</th>
                        <th>名称</th>
                        <th>操作</th>

                    </tr>
                    </thead>
                    <tbody>
                    {% for obj in depart_set %}
                        <tr>
                            <th scope="row">{{ obj.id }}</th>
                            <td>{{ obj.name }}</td>
                            <td>
                                <a class="btn btn-primary btn-xs">编辑</a>
                                <a class="btn btn-danger btn-xs" href="/depart/delete/?departid={{ obj.id }}">删除</a>
                            </td>
                        </tr>
                    {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>


    </div>
</div>


<script src="{% static 'js/jquery-3.6.3.min.js' %}"></script>
<script src="{% static 'plugins/bootstrap-3.4.1/js/bootstrap.js' %}"></script>
</body>
</html>

修改views.py新增depart_delete方法

from django.shortcuts import render, redirect, HttpResponse
from TestManagementSystem import models
# Create your views here.


def depart_list(request):
    """部门列表"""
    # 查询所有部门
    depart_set = models.Department.objects.all()
    return render(request, 'depart_list.html', {"depart_set": depart_set})


def depart_add(request):
    """新增部门"""
    # 新增部门
    # return HttpResponse("成功")
    if request.method =='GET':
        return render(request, 'depart_add.html')
    depart_name = request.POST.get("departname")
    models.Department.objects.create(name=depart_name)
    return redirect('/depart/list')


def depart_delete(request):
    """删除部门"""
    depart_id = request.GET.get("departid")
    models.Department.objects.filter(id=depart_id).delete()
    return redirect('/depart/list')

4、实现部门编辑功能

url注册

"""DjangoDemoOne URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from TestManagementSystem import views

urlpatterns = [
    # path('admin/', admin.site.urls),
    path('depart/list/', views.depart_list),
    path('depart/add/', views.depart_add),
    path('depart/delete/', views.depart_delete),
    path('depart/<int:nid>/edit/', views.depart_edit),
]

修改depart_list编辑页面

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>部门列表</title>
    <link rel="stylesheet" href="{% static 'plugins/bootstrap-3.4.1/css/bootstrap.min.css' %}"/>

</head>
<body>


<nav class="navbar navbar-default">
    <div class="container">  <!-- <div class="container-fluid">  -->
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
                    data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">测试管理系统</a>
        </div>
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav">
                <li><a href="/depart/list/">部门管理</a></li>
                <li><a href="#">Link</a></li>
            </ul>

            <ul class="nav navbar-nav navbar-right">
                <li><a href="#">登录</a></li>
                <li class="dropdown">
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true"
                       aria-expanded="false">春天的菠菜 <span class="caret"></span></a>
                    <ul class="dropdown-menu">
                        <li><a href="#">个人资料</a></li>
                        <li><a href="#">我的信息</a></li>
                        <li role="separator" class="divider"></li>
                        <li><a href="#">注销</a></li>
                    </ul>
                </li>
            </ul>
        </div>
    </div>
</nav>

<div>
    <div class="container">
        <div style="margin-bottom: 10px">
            <a class="btn btn-success" href="/depart/add/">
                <span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span>
                新建
            </a>
        </div>

        <div class="bs-example" data-example-id="panel-without-body-with-table">
            <div class="panel panel-default">
                <!-- Default panel contents -->
                <div class="panel-heading">
                    <span class="glyphicon glyphicon-th-list" aria-hidden="true"></span>
                    部门列表
                </div>

                <!-- Table -->
                <table class="table table-bordered">
                    <thead>
                    <tr>
                        <th>序号</th>
                        <th>名称</th>
                        <th>操作</th>

                    </tr>
                    </thead>
                    <tbody>
                    {% for obj in depart_set %}
                        <tr>
                            <th scope="row">{{ obj.id }}</th>
                            <td>{{ obj.name }}</td>
                            <td>
                                <a class="btn btn-primary btn-xs" href="/depart/{{ obj.id }}/edit/">编辑</a>
                                <a class="btn btn-danger btn-xs" href="/depart/delete/?departid={{ obj.id }}">删除</a>
                            </td>
                        </tr>
                    {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>


    </div>
</div>


<script src="{% static 'js/jquery-3.6.3.min.js' %}"></script>
<script src="{% static 'plugins/bootstrap-3.4.1/js/bootstrap.js' %}"></script>
</body>
</html>

views.py新增depart_edit方法

from django.shortcuts import render, redirect, HttpResponse
from TestManagementSystem import models
# Create your views here.


def depart_list(request):
    """部门列表"""
    # 查询所有部门
    depart_set = models.Department.objects.all()
    return render(request, 'depart_list.html', {"depart_set": depart_set})


def depart_add(request):
    """新增部门"""
    # 新增部门
    # return HttpResponse("成功")
    if request.method =='GET':
        return render(request, 'depart_add.html')
    depart_name = request.POST.get("departname")
    models.Department.objects.create(name=depart_name)
    return redirect('/depart/list')


def depart_delete(request):
    """删除部门"""
    depart_id = request.GET.get("departid")
    models.Department.objects.filter(id=depart_id).delete()
    return redirect('/depart/list')


def depart_edit(request, nid):
    """编辑部门"""
    if request.method == 'GET':
        row_object = models.Department.objects.filter(id=nid).first()
         # print(row_object.id, row_object.name)
        return render(request, 'depart_edit.html', {"row_object": row_object})
    # 获取用户提交的部门名称
    edit_depart_name = request.POST.get("departname")
    # 根据编辑页面用户ID去更新部门的名称
    models.Department.objects.filter(id=nid).update(name=edit_depart_name)
    return redirect('/depart/list')

新增depart_edit.html页面

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>新增部门</title>
    <link rel="stylesheet" href="{% static 'plugins/bootstrap-3.4.1/css/bootstrap.min.css' %}"/>

</head>
<body>


<nav class="navbar navbar-default">
    <div class="container">  <!-- <div class="container-fluid">  -->
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
                    data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">测试管理系统</a>
        </div>
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav">
                <li><a href="/depart/list/">部门管理</a></li>
                <li><a href="#">Link</a></li>
            </ul>

            <ul class="nav navbar-nav navbar-right">
                <li><a href="#">登录</a></li>
                <li class="dropdown">
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true"
                       aria-expanded="false">春天的菠菜 <span class="caret"></span></a>
                    <ul class="dropdown-menu">
                        <li><a href="#">个人资料</a></li>
                        <li><a href="#">我的信息</a></li>
                        <li role="separator" class="divider"></li>
                        <li><a href="#">注销</a></li>
                    </ul>
                </li>
            </ul>
        </div>
    </div>
</nav>

<div>
    <div class="container">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title">新增部门</h3>
            </div>
            <div class="panel-body">
                <form method="post">
                    {% csrf_token %}
                    <div class="form-group">
                        <label>部门名称</label>
                        <input type="text" class="form-control" placeholder="部门名称" name="departname">
                    </div>

                    <button type="submit" class="btn btn-primary">保 存</button>
                </form>
            </div>
        </div>

    </div>
</div>

</body>
</html>

 修改后的值

七、模版的继承

#模版块
{% block content %}{% endblock %}

1、创建模板layout.html

1)将公共的部分写进模版

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    {% block title %}{% endblock %}
    <link rel="stylesheet" href="{% static 'plugins/bootstrap-3.4.1/css/bootstrap.min.css' %}"/>
    <style>
        .navbar{
            border-radius: 0;
        }
    </style>
</head>
<body>


<nav class="navbar navbar-default">
    <div class="container">  <!-- <div class="container-fluid">  -->
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
                    data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">测试管理系统</a>
        </div>
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav">
                <li><a href="/depart/list/">部门管理</a></li>
                <li><a href="#">Link</a></li>
            </ul>

            <ul class="nav navbar-nav navbar-right">
                <li><a href="#">登录</a></li>
                <li class="dropdown">
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true"
                       aria-expanded="false">春天的菠菜 <span class="caret"></span></a>
                    <ul class="dropdown-menu">
                        <li><a href="#">个人资料</a></li>
                        <li><a href="#">我的信息</a></li>
                        <li role="separator" class="divider"></li>
                        <li><a href="#">注销</a></li>
                    </ul>
                </li>
            </ul>
        </div>
    </div>
</nav>

<div>

    {% block content %}{% endblock %}

</div>


<script src="{% static 'js/jquery-3.6.3.min.js' %}"></script>
<script src="{% static 'plugins/bootstrap-3.4.1/js/bootstrap.js' %}"></script>
</body>
</html>

2)后续新的html页面使用下面方法继承模版

{% extends 'layout.html' %}
{% block title %}{% endblock %}
{% block content %}{% endblock %}

2、将depart_list.html页面使用模版重构

{% extends 'layout.html' %}
{% block title %}
    <title>部门列表</title>
{% endblock %}
{% block content %}
    <div class="container">
        <div style="margin-bottom: 10px">
            <a class="btn btn-success" href="/depart/add/">
                <span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span>
                新建
            </a>
        </div>

        <div class="bs-example" data-example-id="panel-without-body-with-table">
            <div class="panel panel-default">
                <!-- Default panel contents -->
                <div class="panel-heading">
                    <span class="glyphicon glyphicon-th-list" aria-hidden="true"></span>
                    部门列表
                </div>

                <!-- Table -->
                <table class="table table-bordered">
                    <thead>
                    <tr>
                        <th>序号</th>
                        <th>名称</th>
                        <th>操作</th>

                    </tr>
                    </thead>
                    <tbody>
                    {% for obj in depart_set %}
                        <tr>
                            <th scope="row">{{ obj.id }}</th>
                            <td>{{ obj.name }}</td>
                            <td>
                                <a class="btn btn-primary btn-xs" href="/depart/{{ obj.id }}/edit/">编辑</a>
                                <a class="btn btn-danger btn-xs" href="/depart/delete/?departid={{ obj.id }}">删除</a>
                            </td>
                        </tr>
                    {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>


    </div>

{% endblock %}

3、将depart_add.html页面重构

{% extends 'layout.html' %}
{% block title %}
    <title>新增部门</title>
{% endblock %}
{% block content %}
    <div class="container">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title">新增部门</h3>
            </div>
            <div class="panel-body">
                <form method="post">
                    {% csrf_token %}
                    <div class="form-group">
                        <label>部门名称</label>
                        <input type="text" class="form-control" placeholder="部门名称" name="departname">
                    </div>

                    <button type="submit" class="btn btn-primary">保 存</button>
                </form>
            </div>
        </div>

    </div>

{% endblock %}

4、将depart_edit.html页面重构

{% extends 'layout.html' %}
{% block title %}
    <title>编辑部门</title>
{% endblock %}
{% block content %}
    <div class="container">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title">编辑部门</h3>
            </div>
            <div class="panel-body">
                <form method="post">
                    {% csrf_token %}
                    <div class="form-group">
                        <label>部门名称</label>
                        <input type="text" class="form-control" placeholder="部门名称" name="departname"  value="{{ row_object.name }}">
                    </div>

                    <button type="submit" class="btn btn-primary">保 存</button>
                </form>
            </div>
        </div>

    </div>
{% endblock %}

八、页面实战-用户管理

1、uri注册

因为和部门管理类似

from django.contrib import admin
from django.urls import path
from TestManagementSystem import views

urlpatterns = [
    # path('admin/', admin.site.urls),
    # 部门管理
    path('depart/list/', views.depart_list),
    path('depart/add/', views.depart_add),
    path('depart/delete/', views.depart_delete),
    path('depart/<int:nid>/edit/', views.depart_edit),
    # 用户管理
    path('user/list/', views.user_list),
    path('user/add/', views.user_add),
    path('user/model/form/add/', views.user_model_form_add),  # 新方法实现
    path('user/<int:nid>/edit/', views.user_edit),
    path('user/<int:nid>/delete/', views.user_delete) # 与部门删除方式不一样
]

2、views.py

新增类

class UserModelForm(forms.ModelForm) 与def user_model_form_add(request)方法
from django.shortcuts import render, redirect, HttpResponse
from TestManagementSystem import models
from django import forms
# Create your views here.


def depart_list(request):
    """部门列表"""
    # 查询所有部门
    print("部门列表")
    depart_set = models.Department.objects.all()
    return render(request, 'depart_list.html', {"depart_set": depart_set})


def depart_add(request):
    """新增部门"""
    # 新增部门
    # return HttpResponse("成功")
    if request.method =='GET':
        return render(request, 'depart_add.html')
    depart_name = request.POST.get("departname")
    models.Department.objects.create(name=depart_name)
    return redirect('/depart/list')


def depart_delete(request):
    """删除部门"""
    depart_id = request.GET.get("departid")
    models.Department.objects.filter(id=depart_id).delete()
    return redirect('/depart/list')


def depart_edit(request, nid):
    """编辑部门"""
    if request.method == 'GET':
        row_object = models.Department.objects.filter(id=nid).first()
         # print(row_object.id, row_object.name)
        return render(request, 'depart_edit.html', {"row_object": row_object})
    # 获取用户提交的部门名称
    edit_depart_name = request.POST.get("departname")
    # 根据编辑页面用户ID去更新部门的名称
    models.Department.objects.filter(id=nid).update(name=edit_depart_name)
    return redirect('/depart/list')


def user_list(request):
    """用户列表"""
    # 查询所有用户
    user_set = models.UserInfo.objects.all()
    """
    for obj in user_set:
        print(obj.id, obj.name, obj.password, obj.account, obj.create_time.strftime("%Y-%m-%d-%H-%M-%S"),
              obj.get_gender_display(), obj.depart.name)
    """
    return render(request, 'user_list.html', {"user_set": user_set})


def user_add(request):
    """新增用户(原始方式)"""

    if request.method == 'GET':
        # 这个是为了新增页面动态获取性别
        context = {
            "gender_choices": models.UserInfo.gender_choices,
            "depart_list": models.Department.objects.all()
        }
        return render(request, 'user_add.html', context)
    user_name = request.POST.get("username")
    password = request.POST.get("pwd")
    age = request.POST.get("age")
    account = request.POST.get("ac")
    create_time = request.POST.get("ctime")
    gender = request.POST.get("gd")
    depart_id = request.POST.get("dp")
    models.UserInfo.objects.create(name=user_name, password=password,
                                   age=age, account=account,
                                   create_time=create_time,
                                   gender=gender, depart_id=depart_id)
    return redirect('/user/list')


class UserModelForm(forms.ModelForm):
    # 限制姓名的长度,至少为3位
    name = forms.CharField(min_length=3, label='用户名')
    # password = forms.CharField(label='密码',validators='这里写正则表达式')

    class Meta:
        model = models.UserInfo
        fields = ["name", "password", "age", "account", "create_time", "gender", "depart"]
        '''widgets = {
            "name": forms.TextInput(attrs={"class": "form-control"}),
            "password": forms.PasswordInput(attrs={"class": "form-control"}),
            "age": forms.TextInput(attrs={"class": "form-control"}),
            "account": forms.TextInput(attrs={"class": "form-control"})           
        }'''  # 下方方法更好

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # 循环找到所有插件,添加了class: "from-control"
        for name, field in self.fields.items():
            field.widget.attrs = {"class": "form-control", "placeholder": field.label}


def user_model_form_add(request):
    """新增用户(ModelForm方式)"""
    if request.method == 'GET':
        form = UserModelForm()
        return render(request, 'user_model_form_add.html', {"form": form})
    # POST 请求提交的数据,数据校验
    form = UserModelForm(data=request.POST)
    if form.is_valid():
        # 如果数据合法,这里判断的是所有字段不能为空,则存储到数据库
        # models.UserInfo.objects.create(..) 常规存储方式
        form.save()
        return redirect('/user/list')
    # 如果不满足if判断进入到else返回错误信息
    return render(request, 'user_model_form_add.html', {"form": form})

3、用户列表页面

{% extends 'layout.html' %}
{% block title %}
    <title>用户列表</title>
{% endblock %}
{% block content %}
    <div class="container">
        <div style="margin-bottom: 10px">
            <a class="btn btn-success" href="/user/add/">
                <span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span>
                新建
            </a>
            <a class="btn btn-success" href="/user/model/form/add/">
                <span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span>
                新建(ModelForm方式)
            </a>
        </div>

        <div class="bs-example" data-example-id="panel-without-body-with-table">
            <div class="panel panel-default">
                <!-- Default panel contents -->
                <div class="panel-heading">
                    <span class="glyphicon glyphicon-th-list" aria-hidden="true"></span>
                    用户列表
                </div>

                <!-- Table -->
                <table class="table table-bordered">
                    <thead>
                    <tr>
                        <th>序号</th>
                        <th>姓名</th>
                        <th>密码</th>
                        <th>年龄</th>
                        <th>余额</th>
                        <th>入职时间</th>
                        <th>性别</th>
                        <th>所属部门</th>
                        <th>操作</th>

                    </tr>
                    </thead>
                    <tbody>
                    {% for obj in user_set %}
                        <tr>
                            <th scope="row">{{ obj.id }}</th>
                            <td>{{ obj.name }}</td>
                            <td>{{ obj.password }}</td>
                            <td>{{ obj.age }}</td>
                            <td>{{ obj.account }}</td>
                            <td>{{ obj.create_time|date:"Y-m-d H:i:s" }}</td>
                            <td>{{ obj.get_gender_display }}</td>
                            <td>{{ obj.depart.name }}</td>
                            <td>
                                <a class="btn btn-primary btn-xs" href="/user/{{ obj.id }}/edit/">编辑</a>
                                <a class="btn btn-danger btn-xs" href="/user/{{ obj.id }}/delete/">删除</a>
                            </td>
                        </tr>
                    {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>


    </div>

{% endblock %}

4、添加用户user_add.html--- 老方法

{% extends 'layout.html' %}
{% block title %}
    <title>新增用户</title>
{% endblock %}
{% block content %}
    <div class="container">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title">新增用户</h3>
            </div>
            <div class="panel-body">
                <form method="post">
                    {% csrf_token %}
                    <div class="form-group">
                        <label>姓名</label>
                        <input type="text" class="form-control" placeholder="姓名" name="username">
                    </div>
                    <div class="form-group">
                        <label>密码</label>
                        <input type="text" class="form-control" placeholder="密码" name="pwd">
                    </div>
                    <div class="form-group">
                        <label>年龄</label>
                        <input type="text" class="form-control" placeholder="年龄" name="age">
                    </div>
                    <div class="form-group">
                        <label>余额</label>
                        <input type="text" class="form-control" placeholder="余额" name="ac">
                    </div>
                    <div class="form-group">
                        <label>入职时间</label>
                        <input type="text" class="form-control" placeholder="入职时间" name="ctime">
                    </div>
                    <div class="form-group">
                        <label>性别</label>
                        <select class="form-control" name="gd">
                            {% for item in gender_choices %}
                            <option value={{ item.0 }}>{{ item.1 }}</option>
                            {% endfor %}
                            <!--<option value="1">男</option>
                            <option value="2">女</option> -->
                        </select>
                    </div>
                    <div class="form-group">
                        <label>所属部门</label>
                        <select class="form-control" name="dp">
                            {% for item in depart_list %}
                            <option value={{ item.id }}>{{ item.name }}</option>
                            {% endfor %}
                        </select>
                    </div>
                    <button type="submit" class="btn btn-primary">保 存</button>
                </form>
            </div>
        </div>

    </div>

{% endblock %}

5、添加用户user_model_form_add.html--- 新方法(ModelForm)

修改model.py

{% extends 'layout.html' %}
{% block title %}
    <title>新增用户(ModelForm)</title>
{% endblock %}
{% block content %}
 <div class="container">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title">新增用户</h3>
            </div>
            <div class="panel-body">
                <form method="post" novalidate>
                    {% csrf_token %}
                    {% for field in form %}
                        <div class="form-group">
                            <label>{{ field.label }}</label>
                            {{ field }}
                            <span style="color: red">{{ field.errors.0 }}</span>
                        </div>
                    {% endfor %}

                    <button type="submit" class="btn btn-primary">保 存</button>
                </form>
            </div>
        </div>

    </div>

{% endblock %}

6、解决提示英文问题

修改settings.py

 7、编辑用户 -新增user_edit.html页面

新增user_edit.html页面(url前面全部配置好了)

{% extends 'layout.html' %}
{% block title %}
    <title>编辑用户</title>
{% endblock %}
{% block content %}
    <div class="container">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title">编辑用户</h3>
            </div>
            <div class="panel-body">
                <form method="post" novalidate>
                    {% csrf_token %}
                    {% for field in form %}
                        <div class="form-group">
                            <label>{{ field.label }}</label>
                            {{ field }}
                            <span style="color: red">{{ field.errors.0 }}</span>
                        </div>
                    {% endfor %}

                    <button type="submit" class="btn btn-primary">保 存</button>
                </form>
            </div>
        </div>

    </div>
{% endblock %}

8、编辑用户 -修改views.py

from django.shortcuts import render, redirect, HttpResponse
from TestManagementSystem import models
from django import forms
# Create your views here.


def depart_list(request):
    """部门列表"""
    # 查询所有部门
    print("部门列表")
    depart_set = models.Department.objects.all()
    return render(request, 'depart_list.html', {"depart_set": depart_set})


def depart_add(request):
    """新增部门"""
    # 新增部门
    # return HttpResponse("成功")
    if request.method =='GET':
        return render(request, 'depart_add.html')
    depart_name = request.POST.get("departname")
    models.Department.objects.create(name=depart_name)
    return redirect('/depart/list')


def depart_delete(request):
    """删除部门"""
    depart_id = request.GET.get("departid")
    models.Department.objects.filter(id=depart_id).delete()
    return redirect('/depart/list')


def depart_edit(request, nid):
    """编辑部门"""
    if request.method == 'GET':
        row_object = models.Department.objects.filter(id=nid).first()
         # print(row_object.id, row_object.name)
        return render(request, 'depart_edit.html', {"row_object": row_object})
    # 获取用户提交的部门名称
    edit_depart_name = request.POST.get("departname")
    # 根据编辑页面用户ID去更新部门的名称
    models.Department.objects.filter(id=nid).update(name=edit_depart_name)
    return redirect('/depart/list')


def user_list(request):
    """用户列表"""
    # 查询所有用户
    user_set = models.UserInfo.objects.all()
    """
    for obj in user_set:
        print(obj.id, obj.name, obj.password, obj.account, obj.create_time.strftime("%Y-%m-%d-%H-%M-%S"),
              obj.get_gender_display(), obj.depart.name)
    """
    return render(request, 'user_list.html', {"user_set": user_set})


def user_add(request):
    """新增用户(原始方式)"""

    if request.method == 'GET':
        # 这个是为了新增页面动态获取性别
        context = {
            "gender_choices": models.UserInfo.gender_choices,
            "depart_list": models.Department.objects.all()
        }
        return render(request, 'user_add.html', context)
    user_name = request.POST.get("username")
    password = request.POST.get("pwd")
    age = request.POST.get("age")
    account = request.POST.get("ac")
    create_time = request.POST.get("ctime")
    gender = request.POST.get("gd")
    depart_id = request.POST.get("dp")
    models.UserInfo.objects.create(name=user_name, password=password,
                                   age=age, account=account,
                                   create_time=create_time,
                                   gender=gender, depart_id=depart_id)
    return redirect('/user/list')


class UserModelForm(forms.ModelForm):
    # 限制姓名的长度,至少为3位
    name = forms.CharField(min_length=3, label='用户名')
    # password = forms.CharField(label='密码',validators='这里写正则表达式')

    class Meta:
        model = models.UserInfo
        fields = ["name", "password", "age", "account", "create_time", "gender", "depart"]
        '''widgets = {
            "name": forms.TextInput(attrs={"class": "form-control"}),
            "password": forms.PasswordInput(attrs={"class": "form-control"}),
            "age": forms.TextInput(attrs={"class": "form-control"}),
            "account": forms.TextInput(attrs={"class": "form-control"})           
        }'''  # 下方方法更好

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # 循环找到所有插件,添加了class: "from-control"
        for name, field in self.fields.items():
            field.widget.attrs = {"class": "form-control", "placeholder": field.label}


def user_model_form_add(request):
    """新增用户(ModelForm方式)"""

    if request.method == 'GET':
        form = UserModelForm()
        return render(request, 'user_model_form_add.html', {"form": form})
    # POST 请求提交的数据,数据校验
    form = UserModelForm(data=request.POST)
    if form.is_valid():
        # 如果数据合法,这里判断的是所有字段不能为空,则存储到数据库
        # models.UserInfo.objects.create(..) 常规存储方式
        form.save()
        return redirect('/user/list')
    # 如果不满足if判断进入到else返回错误信息
    return render(request, 'user_model_form_add.html', {"form": form})


def user_edit(request, nid):
    """编辑用户"""
    # 根据nid去数据库获取所在行数据
    row_object = models.UserInfo.objects.filter(id=nid).first()
    if request.method == 'GET':        
        form = UserModelForm(instance=row_object)
        return  render(request, 'user_edit.html', {"form": form})
    # POST 请求提交的数据,数据校验    
    form = UserModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        # 如果数据合法,这里判断的是所有字段不能为空,则存储到数据库
        # models.UserInfo.objects.create(..) 常规存储方式
        # form.instance.字段名=值  # 如果需要存储用户输入之外的值使用这个
        form.save()
        return redirect('/user/list')
        # 如果不满足if判断进入到else返回错误信息
    return render(request, 'user_edit.html', {"form": form})

9、修改数据库入职时间为年月日格式

 执行命令:

python manage.py makemigrations 
python manage.py migrate

修改user_list.html,删除红色方框

10、删除用户在views.py新增user_delete方法

from django.shortcuts import render, redirect, HttpResponse
from TestManagementSystem import models
from django import forms
# Create your views here.


def depart_list(request):
    """部门列表"""
    # 查询所有部门
    print("部门列表")
    depart_set = models.Department.objects.all()
    return render(request, 'depart_list.html', {"depart_set": depart_set})


def depart_add(request):
    """新增部门"""
    # 新增部门
    # return HttpResponse("成功")
    if request.method =='GET':
        return render(request, 'depart_add.html')
    depart_name = request.POST.get("departname")
    models.Department.objects.create(name=depart_name)
    return redirect('/depart/list')


def depart_delete(request):
    """删除部门"""
    depart_id = request.GET.get("departid")
    models.Department.objects.filter(id=depart_id).delete()
    return redirect('/depart/list')


def depart_edit(request, nid):
    """编辑部门"""
    if request.method == 'GET':
        row_object = models.Department.objects.filter(id=nid).first()
         # print(row_object.id, row_object.name)
        return render(request, 'depart_edit.html', {"row_object": row_object})
    # 获取用户提交的部门名称
    edit_depart_name = request.POST.get("departname")
    # 根据编辑页面用户ID去更新部门的名称
    models.Department.objects.filter(id=nid).update(name=edit_depart_name)
    return redirect('/depart/list')


def user_list(request):
    """用户列表"""
    # 查询所有用户
    user_set = models.UserInfo.objects.all()
    """
    for obj in user_set:
        print(obj.id, obj.name, obj.password, obj.account, obj.create_time.strftime("%Y-%m-%d-%H-%M-%S"),
              obj.get_gender_display(), obj.depart.name)
    """
    return render(request, 'user_list.html', {"user_set": user_set})


def user_add(request):
    """新增用户(原始方式)"""

    if request.method == 'GET':
        # 这个是为了新增页面动态获取性别
        context = {
            "gender_choices": models.UserInfo.gender_choices,
            "depart_list": models.Department.objects.all()
        }
        return render(request, 'user_add.html', context)
    user_name = request.POST.get("username")
    password = request.POST.get("pwd")
    age = request.POST.get("age")
    account = request.POST.get("ac")
    create_time = request.POST.get("ctime")
    gender = request.POST.get("gd")
    depart_id = request.POST.get("dp")
    models.UserInfo.objects.create(name=user_name, password=password,
                                   age=age, account=account,
                                   create_time=create_time,
                                   gender=gender, depart_id=depart_id)
    return redirect('/user/list')


class UserModelForm(forms.ModelForm):
    # 限制姓名的长度,至少为3位
    name = forms.CharField(min_length=3, label='用户名')
    # password = forms.CharField(label='密码',validators='这里写正则表达式')

    class Meta:
        model = models.UserInfo
        fields = ["name", "password", "age", "account", "create_time", "gender", "depart"]
        '''widgets = {
            "name": forms.TextInput(attrs={"class": "form-control"}),
            "password": forms.PasswordInput(attrs={"class": "form-control"}),
            "age": forms.TextInput(attrs={"class": "form-control"}),
            "account": forms.TextInput(attrs={"class": "form-control"})           
        }'''  # 下方方法更好

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # 循环找到所有插件,添加了class: "from-control"
        for name, field in self.fields.items():
            field.widget.attrs = {"class": "form-control", "placeholder": field.label}


def user_model_form_add(request):
    """新增用户(ModelForm方式)"""

    if request.method == 'GET':
        form = UserModelForm()
        return render(request, 'user_model_form_add.html', {"form": form})
    # POST 请求提交的数据,数据校验
    form = UserModelForm(data=request.POST)
    if form.is_valid():
        # 如果数据合法,这里判断的是所有字段不能为空,则存储到数据库
        # models.UserInfo.objects.create(..) 常规存储方式
        form.save()
        return redirect('/user/list')
    # 如果不满足if判断进入到else返回错误信息
    return render(request, 'user_model_form_add.html', {"form": form})


def user_edit(request, nid):
    """编辑用户"""
    # 根据nid去数据库获取所在行数据
    row_object = models.UserInfo.objects.filter(id=nid).first()
    if request.method == 'GET':
        form = UserModelForm(instance=row_object)
        return  render(request, 'user_edit.html', {"form": form})
    # POST 请求提交的数据,数据校验
    form = UserModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        # 如果数据合法,这里判断的是所有字段不能为空,则存储到数据库
        # models.UserInfo.objects.create(..) 常规存储方式
        # form.instance.字段名=值  # 如果需要存储用户输入之外的值使用这个
        form.save()
        return redirect('/user/list')
        # 如果不满足if判断进入到else返回错误信息
    return render(request, 'user_edit.html', {"form": form})


def user_delete(request, nid):
    """删除用户"""
    # 根据nid去数据库获取所在行数据进行删除
    models.UserInfo.objects.filter(id=nid).delete()
    return redirect('/user/list')

源码下载:点我下载

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/358861.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

创建虚拟机,安装CentOS

在VMware上面创建虚拟机 文件->新建虚拟机 选定 自定义的高级&#xff0c;下一步 下一步 检查选定稍后安装操作系统 下一步 选择Linux&#xff0c;CentOS 7 64位 创建虚拟机名称&#xff0c;以及在存放该虚拟机的位置 选择处理器的数量和每个处理器的内核数量 …

Linux入门操作指令介绍(配合Windows理解)

&#xff08;1&#xff09;如果不会装虚拟机和Ubuntu&#xff0c;建议跟着韦东山老师的课程来安装&#xff0c;绝大多数事情他都帮你做好了。跟着视频的来即可。韦东山老师视频链接。&#xff08;2&#xff09;跟着视频做可能还是会有很多不懂的&#xff0c;比如什么是Shell &a…

【论文速递】ACL 2021-CLEVE: 事件抽取的对比预训练

【论文速递】ACL 2021-CLEVE: 事件抽取的对比预训练 【论文原文】&#xff1a;CLEVE: Contrastive Pre-training for Event Extraction 【作者信息】&#xff1a;Wang, Ziqi and Wang, Xiaozhi and Han, Xu and Lin, Yankai and Hou, Lei and Liu, Zhiyuan and Li, Peng and …

【离散数学】3. 代数系统

1.数理逻辑 2. 集合论 3. 代数系统 4. 图论 代数系统&#xff1a;把一些形式上很不相同的代数系统&#xff0c;用统一的方法描述、研究、推理&#xff0c;从而得到反映出他们共性的一些结论&#xff0c;在将结论运用到具体的代数系统中 系统&#xff1a;运算研究对象 运算&…

薪资9k!三年教培老师被优化,选择转行软件测试实现再就业

大学毕业后&#xff0c;我在一家教培机构当了三年的高中英语老师。只是后来我怎么也没想到&#xff0c;这三年间形成的社交圈子和职场经验&#xff0c;仅仅用了三个月便发生了天翻地覆的变化。 ——贵阳校区优秀学员 小Z 01.初入职场 2019年的初夏&#xff0c;我和众多应届毕…

利用redis实现缓存、发布订阅、分布式锁功能

Redis是一个内存键值存储数据库&#xff0c;通常用于缓存、会话管理、消息队列等场景。以下是一些常见的Redis使用场景&#xff1a;1.缓存&#xff1a;将常用的数据缓存在Redis中&#xff0c;以减少对数据库的访问次数&#xff0c;提高应用程序的性能。2.会话管理&#xff1a;使…

用Python采集热门城市景点数据并简单制作数据可视化图

前言 嗨喽~大家好呀&#xff0c;这里是魔王呐 ❤ ~! 模块使用&#xff1a; 爬虫部分: requests parsel csv 数据分析部分: pandas pyecharts 如何安装模块: win R 输入 cmd 输入安装命令&#xff1a; pip install 模块名 回车 pycharm里面安装 terminal 输入安装命令…

OSI七层网络模型

应用层 定义了各种应用协议规范数据格式&#xff1a;HTTP协议、HTTPS协议、FTP协议、DNS协议、TFTP、SMTP等等。 表示层 翻译工作。提供一种公共语言、通信。 会话层 1、可以从校验点继续恢复数据进行重传。——大文件 2、自动收发&#xff0c;自动寻址的功能。 传输层 1、…

Qt下实现不规则形状窗口显示

文章目录前言一、资源文件的添加二、初始化窗口三、重写paintEvent函数实现窗口重绘四、重写QMouseEvent相关函数实现不规则窗口的移动及关闭五、demo完整代码六、下载链接总结前言 本文实现了Qt下显示两个不规则形状的窗口demo&#xff0c;其中有Qt的窗口对话框和QPaintEvent…

基于minikube快速搭建kubernetes单节点环境

一、说明 本文主要介绍在 Centos7 环境下基于 Minikube 来快速部署 Kubernetes 单节点集群环境&#xff0c;并在浏览器上访问部署在 k8s 上的 dashboard 服务。 二、Minikube 介绍 Minikube 是一个基于go语言开发&#xff0c;易于在本地运行 Kubernetes 的工具&#xff0c;可…

《mysql技术内幕:innodb存储引擎》笔记

任何时候Why都比What重要&#xff1b;不要相信任何的“神话”,学会自己思考&#xff1b;不要墨守成规,大部分人都知道的事情可能是错误的&#xff1b;不要相信网上的传言,去测试,根据自己的实践做出决定&#xff1b;花时间充分地思考,敢于提出质疑。1.MYSQL被设计为一个单进程多…

(三十七)vue 项目中常用的2个Ajax库

文章目录axios实现vue-resource实现上一篇&#xff1a;&#xff08;三十六&#xff09;Vue解决Ajax跨域问题 先看一个github搜索案例 有一个搜索框&#xff0c;输入相关用户名&#xff0c;就能模糊搜索出用户&#xff0c;展现到下方 第一步&#xff1a;我们用到了第三方样式库…

36、基于51单片机频率计 LCD 1602显示系统设计

摘要 数字频率计是一种基本的测量仪器。它被广泛应用于航天、电子、测控等领域&#xff0c;还被应用在计算机及各种数学仪表中。一般采用的是十进制数字&#xff0c;显示被测信号频率。基本功能是测量正弦信号&#xff0c;方波信号以及其他各种单位时间内变坏的物理量。由于其…

【沐风老师】为你推荐18个免费3dMAX插件和脚本

在所有 3D 软件中&#xff0c;3dMax的历史特别引人注目&#xff0c;有许多有趣的里程碑和突破点。自 1990 年推出以来&#xff0c;3dMax 一直是Autodesk公司的支柱产品之一。作为行业标准&#xff0c;它是高端项目和各种高级用途的首选 3D 软件之一。 如果你已经在使用3dMax&a…

一站式元数据治理平台——Datahub入门宝典

随着数字化转型的工作推进&#xff0c;数据治理的工作已经被越来越多的公司提上了日程。作为新一代的元数据管理平台&#xff0c;Datahub在近一年的时间里发展迅猛&#xff0c;大有取代老牌元数据管理工具Atlas之势。国内Datahub的资料非常少&#xff0c;大部分公司想使用Datah…

大数据开发-数据仓库介绍

目录标题1、数据仓库1.1 数仓为何而来&#xff1f;1.2 数据仓库的主要特性1.3 数据仓库与数据库的区别1.4 数据仓库三层架构1.5 实战-美团酒旅数仓建设1.6 ETL、ELT1.6.1 ETL1.6.2 ELT1、数据仓库 数据仓库Data Warehouse 简称DH&#xff0c;数据仓库的目的是构建面向分析的集…

Centos7.9源码编译安装dpdk

近日遇到一个需求&#xff0c;需要在Centos7.9上源码编译安装dpdk-21.11.2&#xff0c;并且dpdk的安装目录为/opt/。安装过程较为复杂&#xff0c;特此记录一下&#xff0c;方便日后查看。 相关配置参数编译环境虚拟机Centos7.9内核版本3.10.0-957dpdk版本21.11.2DPDK是INTEL公…

Java并发编程面试题——JUC专题

文章目录一、AQS高频问题1.1 AQS是什么&#xff1f;1.2 唤醒线程时&#xff0c;AQS为什么从后往前遍历&#xff1f;1.3 AQS为什么用双向链表&#xff0c;&#xff08;为啥不用单向链表&#xff09;&#xff1f;1.4 AQS为什么要有一个虚拟的head节点1.5 ReentrantLock的底层实现…

组合实现多类别分割(含实战代码)

来源&#xff1a;投稿 作者&#xff1a;AI浩 编辑&#xff1a;学姐 摘要 segmentation_models_pytorch是一款非常优秀的图像分割库&#xff0c;albumentations是一款非常优秀的图像增强库&#xff0c;这篇文章将这两款优秀结合起来实现多类别的图像分割算法。数据集选用CamVid…

Java实现JDBC工具类DbUtils的抽取及程序实现数据库的增删改操作

封装DbUtils 工具类 不知道我们发现没有&#xff0c;不管是对数据库进行查询&#xff0c;还是标准的JDBC 步骤&#xff0c;其开端都是先实现JDBC 的加载注册&#xff0c;接着是获取数据库的连接&#xff0c;最后都是实现关闭连接&#xff0c;释放资源的操作。那我们何不直接把…