1.优化代码
把form验证的返回报错写成一个共用的类 该类在工程下建立了一个uitls-tools.py
class FormatErrMsg: @property #装饰器-属性方法 调用的时候不需要加() def error_msg(self): #self.get_json_data() 是form自带的友好的报错提示 返回的是一个字典 message = ‘‘ for error_params, v in self.errors.get_json_data().items(): error_message = v[0].get(‘message‘) m = ‘%s:%s‘ % (error_params, error_message) message += m return message
2.单独在工程下面建立一个forms.py文件,用来专门存放form验证,这样就保证views里只写逻辑,而不涉及验证
#创建这个文件专门写forms 验证数据 from django import forms from uitls.tools import FormatErrMsg from . import models #用关联数据库的约束验证form class CaseSetFormALL(forms.ModelForm,FormatErrMsg): class Meta: fields = ‘__all__‘#关联了所有字段 model = models.CaseSet#关联数据库CaseSet exclude = [‘is_delete‘,‘create_time‘,‘update_time‘]#排查不校验的字段 class CaseFormALL(forms.ModelForm,FormatErrMsg): class Meta: fields = ‘__all__‘ model = models.Case exclude = [‘case_set‘,‘create_time‘,‘update_time‘] #自定义 class CaseForm(forms.Form,FormatErrMsg): ‘‘‘校验请求参数‘‘‘ title = forms.CharField(max_length=50,min_length=2) desc = forms.CharField(max_length=70,required=False)#required=False 默认desc可以为空 method = forms.IntegerField() url = forms.URLField() params = forms.CharField(max_length=100) #自定义校验 #单个参数校验@1 # def clean_method(self): # method = self.cleaned_data.get(‘method‘)#先校验上述那些基本的格式,然后在校验自定义的规则 # if method not in (0,1,2,3): # raise ValidationError(‘method值不对‘) # return method # 单个参数校验@2 # def clean_title(self): # title = self.cleaned_data.get(‘title‘) # if models.Case.objects.filter(title=title).count()>0: # raise ValidationError(‘标题重复‘) # return title # def clean(self):#多个参数组合校验‘method‘,‘title‘ # method = self.cleaned_data.get(‘method‘) # title = self.cleaned_data.get(‘title‘) # if method not in (0,1,2,3): # raise forms.ValidationError(‘method参数错误‘)#抛出异常 # elif models.Case.objects.filter(title=title).count()>0: # raise forms.ValidationError(‘标题重复‘)#抛出异常 # return self.cleaned_data class CaseSetForm(forms.Form,FormatErrMsg): name = forms.CharField(max_length=50,min_length=2) desc = forms.CharField(max_length=50,required=False) def clean_name(self): name = self.cleaned_data.get(‘name‘) if models.CaseSet.objects.filter(name=name).count()>0: raise forms.ValidationError(‘用例集合名称重复‘) return name
3.在views.py中写 增删改查的逻辑
from django.forms import model_to_dict,ValidationError from django.http import JsonResponse from django.shortcuts import render from django.views import View from django import forms from . import forms from django.core.paginator import Paginator from . import models from django.db.models import Q from uitls.tools import Page # Create your views here. #常规写法@1,@2,用例集合表 #用例集合添加 post请求 需要传两个参数 即集合表的增加操作@1 def case_set(request): name = request.POST.get(‘name‘) desc = request.POST.get(‘desc‘) if name.strip() and desc.strip() and models.CaseSet.objects.filter(name=name).count()<1: models.CaseSet.objects.create(name=name,desc=desc) data = {‘code‘:0,‘msg‘:‘添加成功‘} else: data = {‘code‘:-1,‘msg‘:‘添加失败‘} return JsonResponse(data) #查询集合 get请求 不需要传参 获取集合表的数据 查询操作@2 def case_set_all(request): case_sets = models.CaseSet.objects.filter(is_delete=False)#查询所有集合 data = [] #把查询出来的转换成字典通过model_to_dict方法,并添加进data列表中,最终返回[{‘xx‘:xx},{‘xx‘:xx}] for c in case_sets: d = model_to_dict(c) data.append(d) response = {‘code‘:0,‘msg‘:‘成功‘,‘data‘:data} return JsonResponse(response,json_dumps_params={‘ensure_ascii‘:False}) #一个函数写两个URL请求的逻辑上述两种方式的结合 def case_set_new(request): name = request.POST.get(‘name‘) desc = request.POST.get(‘desc‘) if request.method==‘GET‘: case_sets = models.CaseSet.objects.filter(is_delete=False) # 查询所有集合 data = [] # 把查询出来的转换成字典通过model_to_dict方法,并添加进data列表中,最终返回[{‘xx‘:xx},{‘xx‘:xx}] for c in case_sets: d = model_to_dict(c) data.append(d) response = {‘code‘: 0, ‘msg‘: ‘成功‘, ‘data‘: data} return JsonResponse(response, json_dumps_params={‘ensure_ascii‘: False}) elif request.method==‘POST‘: if name.strip() and desc.strip() and models.CaseSet.objects.filter(name=name).count()<1: models.CaseSet.objects.create(name=name, desc=desc) data = {‘code‘: 0, ‘msg‘: ‘添加成功‘} else: data = {‘code‘: -1, ‘msg‘: ‘添加失败‘} return JsonResponse(data) #cvb方式,用例集合表,根据请求不同,执行相应的操作 class CaseSet(View): #增加数据 def post(self,request): # form = forms.CaseSetFormALL(request.POST) form = forms.CaseSetForm(request.POST) if form.is_valid(): models.CaseSet.objects.create(**form.cleaned_data) data = {‘code‘: 0, ‘msg‘: ‘添加成功‘} else: data = {‘code‘: -1, ‘msg‘: form.error_msg} return JsonResponse(data) def get_paginator(self,data_list):#分页函数 limit = self.request.GET.get(‘limit‘, 3) # 默认不传 每页显示3条 page_num = self.request.GET.get(‘page_num‘, 1) # 默认不传 显示第一页 paginator = Paginator(data_list,limit) page_data = paginator.page(page_num) return page_data,paginator def get_search_data(self):#模糊查询 data = [] search = self.request.GET.get(‘search‘) if search: data = models.CaseSet.objects.filter(Q(name__contains=search)|Q(desc__contains=search)) return data def get_filter_data(self):#精确查询 data = [] # 定义精确查询的字段为一个列表 filter_field = [‘name‘, ‘desc‘, ‘id‘] filter_dict = {} for field in filter_field: value = self.request.GET.get(field) if value: filter_dict[field] = value if filter_dict: # 精确查询 data = models.CaseSet.objects.filter(**filter_dict) return data #查找数据 def get(self,request): if self.get_filter_data():#调用精确查询函数 case_sets = self.get_filter_data() elif self.get_search_data():#调用模糊查询函数 case_sets = self.get_search_data() else: # 查询所有 case_sets = models.CaseSet.objects.filter(is_delete=False) page_data,paginator = self.get_paginator(case_sets)#调用分页函数 data = [] # 把查询出来的转换成字典通过model_to_dict方法,并添加进data列表中,最终返回[{‘xx‘:xx},{‘xx‘:xx}] for c in page_data: d = model_to_dict(c) data.append(d) response = {‘code‘: 0, ‘msg‘: ‘成功‘, ‘data‘: data,‘count‘:paginator.count}#count是总数据 return JsonResponse(response, json_dumps_params={‘ensure_ascii‘: False}) #cvb方式,用例表 class Case(View): #增加数据 def post(self,request): form = forms.CaseForm(request.POST) #通过post方法拿到请求的数据 # form = forms.CaseFormALL(request.POST)#通过post方法拿到请求的数据 #开始验证 form.is_valid() 返回一个bool类型的数据 通过返回True 不通过返回False if form.is_valid(): #如果校验通过会返回一个字典{‘title‘:xxx,‘desc‘:xxx,‘method‘:xx,‘url‘:xx,‘params‘:xx} # print(form.cleaned_data) models.Case.objects.create(**form.cleaned_data)#字典前面加**转换为title=xxx,desc=xxxx data = {‘code‘: 0, ‘msg‘: ‘成功‘} else: data = {‘code‘: -1, ‘msg‘: form.error_msg} return JsonResponse(data) #查找数据 def get(self,request): case_sets = models.Case.objects.filter(is_delete=False) # 查询所有集合 data = [] # 把查询出来的转换成字典通过model_to_dict方法,并添加进data列表中,最终返回[{‘xx‘:xx},{‘xx‘:xx}] for c in case_sets: d = model_to_dict(c) data.append(d) response = {‘code‘: 0, ‘msg‘: ‘成功‘, ‘data‘: data} return JsonResponse(response, json_dumps_params={‘ensure_ascii‘: False}) #删除数据 def delete(self,request): id = request.GET.get(‘id‘) models.Case.objects.filter(id=id).update(is_delete=True) response = {‘code‘: 0, ‘msg‘: ‘成功‘} return JsonResponse(response, json_dumps_params={‘ensure_ascii‘: False})
原文地址:https://www.cnblogs.com/mhmh007/p/12170762.html
时间: 2024-10-08 23:40:03