【Django】字段信息验证方法

视图views.py文件中,在通过forms.ModelForm来实例化类的时候,进行字段信息的验证:
验证方法一:正则表达式(手机号校验

from django import forms
# 导入正则表达式
from django.core.validators import RegexValidator

class Pattynu(forms.ModelForm):
    # 【正则表达式】校验手机号是否正确
    mobile = forms.CharField(
        label='手机号',
        validators=[RegexValidator(r'^1[3,5,7,8]\d{9}$','手机格式错误!')]  #采用正则进行判断
    )
    class Meta:
        model = Pattynum
        fields = ['mobile','piac','level','ctime','status']      

验证方法二:钩子方法(手机号位数校验
钩子方法:def clean_字段名(self)

from django import forms
# 钩子方法 返回错误信息
from django.core.exceptions import ValidationError
class Pattynu(forms.ModelForm):    
    class Meta:
        model = Pattynum    #原来model.py定义表结构类名要同名
        fields = ['mobile','piac','level','ctime','status']    

    # 【钩子方法】校验手机号是否正确
    def clean_mobile(self):        # def clean_字段名(self),默认为钩子方法,每个字段都有
        text_mobile = self.cleaned_data['mobile']
        if len(text_mobile) != 11:
            raise ValidationError('格式错误')
        return text_mobile

验证方法三:钩子方法(手机号数据库是否存在校验
【添加时】:

from django.core.validators import ValidationError
    def clean_ipone(self):
        text_ipone = self.cleaned_data['ipone']   # 获取要输入ipone的值 
        exist = Psons.objects.filter(ipone=text_ipone).exists()   # 添加时候数据库是否存在
        if exist:
            raise ValidationError('手机号已存在')
        return text_ipone

【编辑时】:

from django.core.validators import ValidationError
    def clean_ipone(self):
        text_ipone = self.cleaned_data['ipone']   # 获取要输入ipone的值
        text_id = self.instance.pk    # 获取当前正在编辑的id
        exist = Psons.objects.filter(ipone=text_ipone).exclude(id=text_id).exists()  # 编辑时候,排除当前自己,是否存在
        if exist:
            raise ValidationError('手机号已存在')
        return text_ipone
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值