九、django通过forms对页面数据校验

以一个student学生表为例子
class  Student(models.Model):
    name = models.CharField(verbose_name='名称',max_length=10)
    phone = models.CharField(max_length=11,unique=True,verbose_name='手机号')
    money = models.FloatField(verbose_name='',default=0,null=True)

    class Meta:
        verbose_name = '学生表'
        verbose_name_plural = verbose_name
        db_table = 'student'

    def __str__(self):
        return self.name

校验代码实现
views.py
from django import forms  #校验
from django.core.exceptions import ValidationError #异常

#写一个校验的类,用于校验数据
class StudentForm(forms.Form):
    # 校验的类
    name = forms.CharField(min_length=2,max_length=10)
    phone = forms.CharField(min_length=11,max_length=11)
    money = forms.FloatField(required=False)# required=True 必传,默认就是True
    def clean_phone(self):
        '''钩子,自定义校验规则,函数名是clean_字段名 '''
        phone = self.cleaned_data['phone'] #把数据中的phone数据拿过来
        if models.Student.objects.filter(phone=phone):
            raise ValidationError('手机号已存在')
        return phone

#页面的后台函数
def student(request):
    stu_form = StudentForm(request.POST) #校验的类
    if stu_form.is_valid(): # is_valid如果这是合法的
        print('cleaned_data',stu_form.cleaned_data)
        models.Student.objects.create(**stu_form.cleaned_data)
        data = {"msg":"成功"}
    else:
        print('errors',stu_form.errors.get_json_data())
        data = {"msg":"校验失败"}
    return HttpResponse(json.dumps(data,ensure_ascii=False))

posted @ 2019-10-26 18:16  颜颜blog  阅读(215)  评论(0编辑  收藏  举报