python - 验证已经存在的数据禁止 添加


添加数据 : 

    # 方法2  钩子方法  clean_字段名(self)
    # 校验已经存在的手机号 禁止入库
    def clean_mobile(self):

        # 获取用户传入的数据
        text_mobile = self.cleaned_data['mobile']
        # exists() 验证手机号是否存在
        exists = models.Number.objects.filter(mobile=text_mobile).exists()
        if exists:
            # 使用 ValidationError 需要引入 from django.core.exceptions import ValidationError
            # 验证不通过
            raise ValidationError('手机号已经存在')

        # 验证通过
        return text_mobile

手机号码 11 的验证方式 :


 # 方法2  钩子方法  clean_字段名(self)
    # 校验已经存在的手机号 禁止入库
    def clean_mobile(self):

        # 获取用户传入的数据
        text_mobile = self.cleaned_data['mobile']
     if len(text_mobile) != 11:  # 也可以判断手机号码是不是 11位
       raise ValidationError('手机号已经存在')  
 # 验证通过
        return text_mobile

      

 添加手机号 

'''手机靓号列表'''
def number_list(request):

    # 搜索数据
    data_dict = {}
    search_data = request.GET.get('q', '')
    if search_data:
        data_dict['mobile__contains'] = search_data

    queryset = models.Number.objects.filter(**data_dict).order_by('id')

    # 引入自定义的组件

    page_object = Pagetions(request, queryset)
    context = {
        'queryset': page_object.page_queryset,
        'search_data': search_data,
        'page_string': page_object.html()
    }
    return render(request, 'number_list.html',context )

'''增加靓号'''
from django.core.validators import RegexValidator
class NumberModelForm(forms.ModelForm):

    # 重新定义一次 手机号的格式问题
    mobile = forms.CharField(
        label='手机号',
        validators = [RegexValidator(r'^1[3-9]\d{9}$', '手机号格式错误')],
    )

    class Meta:
        model = models.Number
        # 1. 方法1  fields = ['mobile', 'price', ji, zhuang ] 使用的字段
        # 2. 方法2  exclude = ['mobile']  排除的字段
        # 3. 方法3  fields = '__all__' 全部字段
        fields = '__all__'

        # 重定义方法 添加input 样式
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 循环出所有字段, 并用插件 插入 clas 样式
        for name, field in self.fields.items():
            # if name == 'name':
            #     continue
            field.widget.attrs = {"class": "form-control", "placeholder": field.label}


    # 方法2  钩子方法  clean_字段名(self)
    # 校验已经存在的手机号 禁止入库
    def clean_mobile(self):

        # 获取用户传入的数据
        text_mobile = self.cleaned_data['mobile']
        # exists() 验证手机号是否存在
        exists = models.Number.objects.filter(mobile=text_mobile).exists()
        if exists:
        #if len(text_mobile) != 11:  # 也可以判断手机号码是不是 11位

            # 使用 ValidationError 需要引入 from django.core.exceptions import ValidationError
            # 验证不通过
            raise ValidationError('手机号已经存在')

        # 验证通过
        return text_mobile

相关