测试平台开发(五)Django实现项目管理功能
一、创建用户应用
打开 Tools > Run manage.py Task…,运行 startapp空格加应用名称
startapp projects
生成应用后一定要记得将应用名加入到settings.py文件里名为INSTALLED_APPS的列表中,遵循规范加入到列表的最后,再添加应用也一样
1 # settings.py 2 INSTALLED_APPS=[ 3 ……, 4 'projects', 5 ]
二、编写数据模型
1 # projects/models.py 2 from django.db import models 3 4 from utils.base_models import BaseModel 5 6 7 class Projects(BaseModel): 8 id = models.AutoField(primary_key=True, verbose_name='id主键') 9 name = models.CharField(max_length=50, unique=True, verbose_name='项目名') 10 leader = models.CharField(max_length=50, verbose_name='负责人') 11 tester = models.CharField(max_length=50, verbose_name='测试人员') 12 programer = models.CharField(max_length=50, verbose_name='开发人员') 13 publish_app = models.CharField(max_length=50, verbose_name='应用名称') 14 desc = models.CharField(max_length=200, verbose_name='简要描述', blank=True, default="", null=True) 15 16 class Meta: 17 db_table = 'lx_projects' 18 verbose_name = '项目信息' 19 verbose_name_plural = verbose_name 20 21 def __str__(self): 22 return self.name
迁移数据库,打开 Tools > Run manage.py Task…,依次行
makemigrations
migrate
三、编写视图函数
1.表单校验,在projects目录下创建forms.py文件,用来校验创建项目数据和修改时输入的数据
1 # projects/forms.py 2 from django import forms 3 from django.core.exceptions import ValidationError 4 5 from projects.models import Projects 6 7 8 class CreateForm(forms.Form): 9 name = forms.CharField( 10 label="项目名", 11 required=True, 12 max_length=50, 13 min_length=2, 14 error_messages={ 15 "required": "项目名不能为空", 16 "max_length": "项目名最长不能超过50个字符", 17 "min_length": "项目名最小长度为2" 18 }) 19 leader = forms.CharField( 20 label="负责人", 21 required=True, 22 max_length=50, 23 min_length=2, 24 error_messages={ 25 "required": "负责人不能为空", 26 "max_length": "负责人最长不能超过50个字符", 27 "min_length": "负责人最小长度为2" 28 }) 29 tester = forms.CharField( 30 label="测试人员", 31 required=True, 32 max_length=50, 33 min_length=2, 34 error_messages={ 35 "required": "测试人员不能为空", 36 "max_length": "测试人员最长不能超过50个字符", 37 "min_length": "测试人员最小长度为2" 38 }) 39 programer = forms.CharField( 40 label="开发人员", 41 required=True, 42 max_length=50, 43 min_length=2, 44 error_messages={ 45 "required": "开发人员不能为空", 46 "max_length": "开发人员最长不能超过50个字符", 47 "min_length": "开发人员最小长度为2" 48 }) 49 publish_app = forms.CharField( 50 label="应用名称", 51 required=True, 52 max_length=50, 53 min_length=2, 54 error_messages={ 55 "required": "应用名称不能为空", 56 "max_length": "应用名称最长不能超过50个字符", 57 "min_length": "应用名称最小长度为2" 58 }) 59 desc = forms.CharField( 60 label="简要描述", 61 required=False, 62 max_length=200, 63 error_messages={ 64 "max_length": "简要描述最长不能超过200个字符", 65 }) 66 67 def clean_name(self): 68 val = self.cleaned_data.get("name") 69 ret = Projects.objects.filter(name=val).values("name") 70 if not ret: 71 return val 72 else: 73 raise ValidationError("该项目名已存在!") 74 75 76 class UpdateForm(forms.Form): 77 name = forms.CharField( 78 label="项目名", 79 required=False, 80 max_length=50, 81 min_length=2, 82 error_messages={ 83 "max_length": "项目名最长不能超过50个字符", 84 "min_length": "项目名最小长度为2" 85 }) 86 leader = forms.CharField( 87 label="负责人", 88 required=False, 89 max_length=50, 90 min_length=2, 91 error_messages={ 92 "max_length": "负责人最长不能超过50个字符", 93 "min_length": "负责人最小长度为2" 94 }) 95 tester = forms.CharField( 96 label="测试人员", 97 required=False, 98 max_length=50, 99 min_length=2, 100 error_messages={ 101 "max_length": "测试人员最长不能超过50个字符", 102 "min_length": "测试人员最小长度为2" 103 }) 104 programer = forms.CharField( 105 label="开发人员", 106 required=False, 107 max_length=50, 108 min_length=2, 109 error_messages={ 110 "max_length": "开发人员最长不能超过50个字符", 111 "min_length": "开发人员最小长度为2" 112 }) 113 publish_app = forms.CharField( 114 label="应用名称", 115 required=False, 116 max_length=50, 117 min_length=2, 118 error_messages={ 119 "max_length": "应用名称最长不能超过50个字符", 120 "min_length": "应用名称最小长度为2" 121 }) 122 desc = forms.CharField( 123 label="简要描述", 124 required=False, 125 max_length=200, 126 error_messages={ 127 "max_length": "简要描述最长不能超过200个字符", 128 })
2.在utils目录下的common.py文件写入一个字典去除空值的函数,下面回用到
1 # utils/common.py 2 …… 3 4 def removeEmpty(data): 5 data2 = {} 6 for o in data: 7 if not data[o] == '': 8 data2[o] = data[o] 9 return data2
3.编写用户应用的视图函数
1 # projects/views.py 2 from django.http import JsonResponse 3 from django.views import View 4 from django.core.paginator import Paginator 5 6 from projects.forms import CreateForm, UpdateForm 7 from projects.models import Projects 8 from utils.common import result, removeEmpty 9 from utils.jwt_permission_required import auth_permission_required 10 11 12 class CreateListView(View): 13 # 分页 + 项目名模糊查询 14 @auth_permission_required("class_func") 15 def get(self, request): 16 result["message"] = "查询成功" 17 result["success"] = True 18 page = request.GET.get("page", 1) 19 size = request.GET.get("size", 10) 20 name = request.GET.get("name", "") 21 projects = Projects.objects.filter(is_delete=False, name__contains=name) 22 projectss = Paginator(projects, size) 23 project_list = [] 24 for project in projectss.page(page): 25 project_list.append({ 26 'id': project.id, 27 'name': project.name, 28 'leader': project.leader, 29 'tester': project.tester, 30 'programer': project.programer, 31 'publish_app': project.publish_app, 32 'desc': project.desc 33 }) 34 result["details"] = { 35 "records": project_list, 36 "pages": projectss.num_pages, 37 "total": projectss.count 38 } 39 # JsonResponse第一个参数默认只能为dict字典,如果设为其他类型,需要将safe设为False 40 return JsonResponse(result, safe=False, status=200) 41 42 # 创建数据 43 @auth_permission_required("class_func") 44 def post(self, request): 45 result["message"] = "保存失败" 46 result["success"] = False 47 result["details"] = None 48 json_data = request.body.decode('utf-8') 49 if json_data: 50 python_data = eval(json_data) 51 data = CreateForm(python_data) 52 if data.is_valid(): 53 print(data.cleaned_data) 54 Projects.objects.create(**data.cleaned_data) 55 result["message"] = "保存成功" 56 result["success"] = True 57 result["details"] = data.cleaned_data 58 return JsonResponse(result, status=200) 59 else: 60 result["details"] = data.errors 61 return JsonResponse(result, status=400) 62 return JsonResponse(result, status=500) 63 64 65 class UpdateDeleteView(View): 66 # 更新数据 67 @auth_permission_required("class_func") 68 def put(self, request, pk): 69 result["message"] = "更新失败" 70 result["success"] = False 71 result["details"] = None 72 ret = Projects.objects.filter(id=pk, is_delete=False).values("id") 73 if ret: 74 json_data = request.body.decode('utf-8') 75 if json_data: 76 python_data = eval(json_data) 77 data = UpdateForm(python_data) 78 if data.is_valid(): 79 a = Projects.objects.filter(name=python_data["name"]).values("id").first() 80 if not a or a["id"] == pk: 81 d = removeEmpty(data.cleaned_data) 82 Projects.objects.filter(id=pk).update(**d) 83 result["message"] = "更新成功" 84 result["success"] = True 85 result["details"] = d 86 return JsonResponse(result, status=200) 87 else: 88 result["details"] = "该项目名已存在" 89 return JsonResponse(result, status=400) 90 else: 91 result["details"] = data.errors 92 return JsonResponse(result, status=400) 93 return JsonResponse(result, status=500) 94 else: 95 result["details"] = "项目不存在" 96 return JsonResponse(result, status=400) 97 98 # 逻辑删除 99 @auth_permission_required("class_func") 100 def delete(self, request, pk): 101 result["message"] = "删除失败" 102 result["success"] = False 103 result["details"] = None 104 ret = Projects.objects.filter(id=pk, is_delete=False).values("id").first() 105 if ret: 106 project = Projects.objects.get(id=pk) 107 project.is_delete = True 108 project.save() 109 result["message"] = "删除成功" 110 result["success"] = True 111 return JsonResponse(result, status=200) 112 result["details"] = "项目不存在" 113 return JsonResponse(result, status=400) 114 115 # 获取id和name 116 @auth_permission_required("func") 117 def names(reuqest): 118 result["message"] = "查询成功" 119 result["success"] = True 120 projects = Projects.objects.filter(is_delete=False).values("id", "name") 121 project_list = [] 122 for project in projects: 123 project_list.append({ 124 'id': project["id"], 125 'name': project["name"], 126 }) 127 result["details"] = project_list 128 return JsonResponse(result, safe=False, status=200)
四、编写应用的路由
在projects目录下创建urls.py文件
1 #projects/urls.py 2 from django.urls import path 3 4 from projects import views 5 6 urlpatterns = [ 7 path('', views.CreateListView.as_view()), 8 path('<int:pk>', views.UpdateDeleteView.as_view()), 9 path('names',views.names) 10 ]
五、定义全局路由
1 # testplatform/urls.py 2 from django.contrib import admin 3 from django.urls import path, include 4 5 urlpatterns = [ 6 path('api/admin/', admin.site.urls), 7 path('api/user/', include("users.urls")), 8 path('api/project/', include("projects.urls")) 9 ]
六、测试
1. 分页+项目名模糊查询
2. 创建数据
3. 更新数据
4. 逻辑删除
5. 获取id和name
GitHub持续更新:地址https://github.com/debugf/testplatform
转载请注明出处,商用请征得作者本人同意,谢谢!!!