django前后端分离_02(form的验证)

django为了方便验证请求的参数,使用了form模块,在form中我们可以使用它的基本校验规则,也可以自定义校验规则

使用了 模块需要导入

from django import forms

from django.forms import ValidationError

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 models
#cvb方式,用例表

#form django自带的数据校验模块
class CaseForm(forms.Form):
    '''校验请求参数'''
    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 = self.cleaned_data.get('method')
        title = self.cleaned_data.get('title')
        if method not in (0,1,2,3) or models.Case.objects.filter(title=title).count()>0:
            raise ValidationError('参数错误12313123213')#抛出异常
        return self.cleaned_data

class CaseView(View):
    #增加数据
    def post(self,request):
        form = CaseForm(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:
            #form.errors.as_data() 是form自带的友好提示
            data = {'code': -1, 'msg': str(form.errors.as_data())}
        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})

实现原理

 

posted @ 2020-01-07 17:06  小马哥007  阅读(840)  评论(0编辑  收藏  举报