目录
一、创建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 %}
<form method="post">
{% csrf_token %}
{% for field in form %}
{{ field.label }}:{{ field }}
{% endfor %}
</form>
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')
源码下载:点我下载