form 提交验证数据库是否存在

单个错误第一种方式

修改原码方式



代码:

def ajax(request):
    if request.method == 'GET':
        obj = forms.UserForm()
        return render(request,'ajax.html',{'obj':obj})
    else:
        ret = {'status':False,'message':None}
        import json
        obj = forms.UserForm()
        if obj.is_valid():
            # 登录验证数据库是否存在
            print(obj.cleaned_data)
            if models.Users.objects.filter(username=obj.username).count(): # 数据库是否存在
                obj.errors['username'] = ['用户名已存在']
            if models.Users.objects.filter(email=obj.email).filter().count():
                obj.errors['email'] = ['email已存在']
            ret['status'] = True
            return HttpResponse(json.dumps(ret))
 from django.core.exceptions import NON_FIELD_ERRORS, ValidationError
 # 验证数据库是否存在
 class AjaxForm(forms.Form):
     username = fields.IntegerField()
     user_id = fields.IntegerField(
         widget=widgets.Select(choices=[(0,'q'),(1,'w')])
     )
     # 数据已经存到obj.cleaned_data
     # 之后调用 clean_%s
     # 必须有返回值
     # 如果出错:raise ValidationError('已存在')
     # 异常捕捉 ValidationError   只能捕捉这个异常
     def clean_username(self):
         v = self.cleaned_data['username']
         if models.Users.objects.filter(username=v).count():
             raise ValidationError('用户名已存在')
     def clean_user_id(self):
         return self.cleaned_data['user_id']           

整体错误

代码

 def clean(self):
        value_dict = self.cleaned_data
        v1 = value_dict.get('username')
        v2 = value_dict.get('user_id')
        if v1 == 'root' and v2 == 1:
            raise ValidationError('整体错误信息')
        return self.cleaned_data

# 单个错误信息 前端放到字段名中 
# 前端取出错误信息 .__all__ 可以取出整体错误信息
#  _post_clean()方法 自定制 自己做异常处理


自定义密码

 登录,注册
        - 密码:数字,字母,特殊字符
        - 密码两次输入一致
        
        提交:
            v = MyForm(request.GET) # 6个字段
            if v.is_valid():
                pass
        
        密码示例:RegexField自定义密码验证规则
        
            password = forms.RegexField(
                '^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[!@#$\%\^\&\*\(\)])[0-9a-zA-Z!@#$\%\^\&\*\(\)]{8,32}$',
                min_length=12,
                max_length=32,
                error_messages={'required': '密码不能为空.',
                                'invalid': '密码必须包含数字,字母、特殊字符',
                                'min_length': "密码长度不能小于8个字符",
                                'max_length': "密码长度不能大于32个字符"}
            )
              
            class RegisterForm(BaseForm, django_forms.Form):
                username = django_fields.CharField()
                password = django_fields.CharField()
                confirm_pwd = django_fields.CharField()

                def clean(self):
                    v1 = self.cleaned_data['password']
                    v2 = self.cleaned_data['confirm_pwd']
                    if v1 == v2:
                        pass
                    else:
                        from django.core.exceptions import ValidationError
                        raise ValidationError('密码输入不一致')
        
            
            def register(request):
                v = RegisterForm(request.POST)
                if v.is_valid():
                    pass
                else:
                    v.errors['username']
                    v.errors['__all__']
                    v.errors[NON_FIELD_ERRORS]
                    {
                        __all__: [],
                        username: [],
                        password: []
                        confirm_pwd: []
                    }
                
                return render(request, 'register.html', {'v':v})
                
                
            register.html
            
                {{v.errors.username.0}}
                
                {{v.non_field_errors}}









阅读更多
换一批

没有更多推荐了,返回首页