基于Django框架 CRM的增删改查
思路: 创建表------从数据库读出数据展示出来------配置路由-----写视图函数------写对应页面
练习点:
数据库建表
ORM 数据库数据读取 数据
ModelForm (form组件是基础)
模板渲染在页面上循环取出form里字段的数据
拾遗:
在html中 可以使用 forloop.counter 在页面显示编号的序列, 而不是直接显示数据库里对应的 id 号
<td>{{ field.id }}</td>#}
<!--不会显示出来后端数据库的id字段 -->
<td>{{ forloop.counter }}</td>
在 Employee 的 model中 一个 gender 字段
gender = models.IntegerField(choices=((1,"男"),(2,"女")))
在 html 中
<td>{{ field.get_gender_display }}</td>
<!-- 拿到元组choices 第二个值 "男" 页面不显示 1 -->
<tbody> {% for field in employee_queryset %} <tr><!--不会显示出来后端数据库的id字段 --> <td>{{ forloop.counter }}</td> <td>{{ field.employee_name }}</td>
<td>{{ field.get_gender_display }}</td> <!--拿到元组第二个值 "男" 页面不显示1--> <td>{{ field.department.name }}</td> <td><a href="/edit_employee/{{ field.pk }}">编辑</a></td> <td><a href="/delete_employee/{{ field.pk }}">删除</a></td> </tr> {% endfor %} </tbody>
1. 创建表
部门表
员工表 (和部门表 多对一的关系)
员工角色表 (和部门表 多对多的关系)
from django.db import models class Employee(models.Model): # id = models.AutoField(primary_key=True) employee_name = models.CharField(max_length=32) gender = models.IntegerField(choices=((1,"男"),(2,"女"))) department = models.ForeignKey(to="Department",to_field="id",on_delete=models.CASCADE) duty = models.ManyToManyField(to="Duty") class Department(models.Model): # id = models.AutoField(primary_key=True) name = models.CharField(max_length=32, null=True) employee_num = models.CharField(max_length=32) def __str__(self): return self.name class Duty(models.Model): # id = models.AutoField(primary_key=True) name = models.CharField(max_length=32) def __str__(self): return self.name
2. 部门表的操作
2.1 从数据库取出数据 显示部门列表
from app01.models import Department,Employee from django.shortcuts import render, HttpResponse, redirect from django import forms # --------------部门 读取数据 显示到页面------------------------------------ def index(request): dep_queryset=Department.objects.all() print(dep_queryset) return render(request,"index.html",{"dep_queryset":dep_queryset})
------------- 显示到 html页面
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> INDEX <hr> <a href="/add/">添加部门</a> <table> <thead> <tr> <th>编号</th> <th>部门名称</th> <th>部门人数</th> <th>操作</th> </tr> </thead> <tbody> {% for field in dep_queryset %} <tr> {# <td>{{ field.id }}</td>#} <!--不把数据库的id显示出来 --> <td>{{ forloop.counter}}</td> <td>{{ field.name }}</td> <td>{{ field.employee_num }}</td> <td><a href="/edit/{{ field.pk }}">编辑</a></td> <td><a href="/delete/{{ field.pk }}">删除</a></td> </tr> {% endfor %} </tbody> </table> </body> </html>
2.2 添加 (使用 ModelForm 实现)
2.2.1. 创建 部门的 ModelForm 类
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class DepartmentModelForm(forms.ModelForm): class Meta: model=Department #加参数 fields="__all__" #表示所有字段 # 全局设置, 没有加label的字段就还是按字段名 labels={ "id":"部门编号", "name":"部门名称", "employee_num":"部门人数", } #初始化把样式调出来 def __init__(self,*args,**kwargs): super().__init__(*args, **kwargs) # 父类里面的__init__ # 调节id name employee_num 样式 print(self.fields,type(self.fields)) for field in self.fields.values(): field.error_messages = {"required": "不能为空"} # 批量处理
2.2.2. 添加数据
先走get请求获取页面 在走一边post请求 添加
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
def add(request): if request.method == "GET" : form = DepartmentModelForm() return render(request,"add.html",{"form":form}) else: form = DepartmentModelForm(request.POST) if form.is_valid(): form.save() #取出数据 绑定关系 ret=index(request) return ret # return redirect(request,"index.html") else: return render(request, "add.html", {"form": form})
2.2.3. 渲染的html页面 (添加部门)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h3> 添加部门 </h3> <form action="" method="post" novalidate> {% csrf_token %} {% for field in form %} <div class="form-group"> <label for="title">{{ field.label }}</label> {{ field }} <span>{{ field.errors.0 }}</span> </div> {% endfor %} <input type="submit" value="提交"> </form> </body> </html>
2.3 编辑 (ModelForm)
编辑和添加的步奏基本是一样 唯一不同的一点就是 编辑需要传入一个参数 这个参数代表的是被删除的数据的id
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
def edit(request,id): edit_num = Department.objects.filter(pk=id).first() # 被编辑的 if request.method == "GET" : form = DepartmentModelForm(instance=edit_num) # 直接把被编辑的对象之前的值显示出来 # 不含instance 显示出来的input标签内是空的 就是一个添加页面 return render(request,"edit.html",{"form":form}) else: edit_num = Department.objects.filter(pk=id).first() # 被编辑的 form = DepartmentModelForm(request.POST,instance=edit_num) if form.is_valid(): form.save() #取出数据 绑定关系 ret=index(request) return ret # return redirect(request,"index.html") else: return render(request, "edit.html", {"form": form})
渲染的html页面
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h3> 编辑 </h3> <form action="" method="post" novalidate> {% csrf_token %} {% for field in form %} <div class="form-group"> <label for="title">{{ field.label }}</label> {{ field }} <span>{{ field.errors.0 }}</span> </div> {% endfor %} <input type="submit" value="提交"> </form> </body> </html>
2.4 删除
删除就是要找到需要被删除数据对应的id号 即可
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
def delete(request,id): Department.objects.filter(pk=id).delete() ret = index(request) return ret # return redirect(request,"index.html")
3. 员工表的操作
3.1 从数据库取出数据 页面显示员工列表
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
def employee_index(request): employee_queryset = Employee.objects.all() return render(request, "employee.html", {"employee_queryset": employee_queryset})
html 页面的显示
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> 员工表 <hr> <a href="/add_employee/">添加员工信息</a> <table> <thead> <tr> <th>编号</th> <th>姓名</th> <th>性别</th> <th>部门</th> </tr> </thead> <tbody> {% for field in employee_queryset %} <tr> {# <td>{{ field.id }}</td>#} <!--不会显示出来后端数据库的id字段 --> <td>{{ forloop.counter }}</td> <td>{{ field.employee_name }}</td> <td>{{ field.get_gender_display }}</td> <!--拿到元组第二个值 "男" 页面不显示1--> <td>{{ field.department.name }}</td> <td><a href="/edit_employee/{{ field.pk }}">编辑</a></td> <td><a href="/delete_employee/{{ field.pk }}">删除</a></td> </tr> {% endfor %} </tbody> </table> </body> </html>
3.2 添加 (ModelForm)
3.2.1 创建一个员工 EmployeeModelForm 的类
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class EmployeeModelForm(forms.ModelForm): class Meta: model = Employee # 加参数 fields = "__all__" # 表示所有字段 labels={ "id": "员工编号", "employee_name": "员工姓名", "gender": "性别", "department": "所在部门", "duty": "职责", } # 初始化把样式调出来 def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # 父类里面的__init__ # 调节id name gender department duty 样式 print(self.fields, type(self.fields)) for field in self.fields.values(): field.error_messages = {"required": "不能为空"} # 批量处理
3.2.2 添加数据
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
def employee_add(request): if request.method == "GET": form = EmployeeModelForm() return render(request,"add_employee.html",{"form":form}) else: form = EmployeeModelForm(request.POST) if form.is_valid(): form.save() ret= employee_index(request) return ret else: return render(request,"add_employee.html",{"form":form})
3.2.3 渲染的html页面
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h3> 添加员工 </h3> <form action="" method="post"> {% csrf_token %} {% for field in form %} <div class="form-group"> <label for="title">{{ field.label }}</label> {{ field }} <span>{{ field.errors.0 }}</span> </div> {% endfor %} <input type="submit" value="提交"> </form> </body> </html>
3.3 编辑 (ModelForm)
编辑和添加的步奏基本是一样 唯一不同的一点就是 编辑需要传入一个参数 这个参数代表的是被删除的数据的id
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
def employee_edit(request,id): edit_num = Employee.objects.filter(pk=id).first() # 被编辑的 if request.method == "GET" : form = EmployeeModelForm(instance=edit_num) # 直接把被编辑的对象之前的值显示出来 # 不含instance 显示出来的input标签内是空的 就是一个添加页面 return render(request,"edit_employee.html",{"form":form}) else: edit_num = Employee.objects.filter(pk=id).first() # 被编辑的 form = EmployeeModelForm(request.POST,instance=edit_num) if form.is_valid(): form.save() #取出数据 绑定关系 ret=employee_index(request) return ret # return redirect(request,"index.html") else: return render(request, "edit_employee.html", {"form": form})
渲染的html
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h3> 添加员工 </h3> <form action="" method="post"> {% csrf_token %} {% for field in form %} <div class="form-group"> <label for="title">{{ field.label }}</label> {{ field }} <span>{{ field.errors.0 }}</span> </div> {% endfor %} <input type="submit" value="提交"> </form> </body> </html>
3.4 删除
删除就是要找到需要被删除数据对应的id号 即可
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
def employee_delete(request,id): Employee.objects.filter(pk=id).delete() ret = employee_index(request) return ret