Django - Custom Form validation rules

Custom Form validation rules

class MyForm(forms.Form):
    # form可以校验的规则
    username = fields.CharField(max_length=32,min_length=3)  
    password = fields.CharField(max_length=32,min_length=3)
    re_password = fields.CharField(max_length=32,min_length=3)   

Local hook - validate the user name can not be repeated

def clean_username(self):
    # 获取username
    username = self.cleaned_data['username']

    # 判断用户名是否存在
    if models.User.objects.filter(username=username).count():
        # 存在即不符合规则,必须抛出ValidationError异常
        raise ValidationError('该用户名已存在')
    # 校验通过,则返回清洗后的数据
    return self.cleaned_data['username']

Global hooks - Inspection enter the same password twice

def clean(self):
    # 获取两次输入的密码
    password = self.cleaned_data['password']
    re_password = self.cleaned_data['re_password']
    
    # 判断是否相等,相等则返回数据,否则抛出ValidationError异常
    if password == re_password:
        return self.cleaned_data
    else:
        raise ValidationError('两次密码输入不一致')

Note: the function name and the local hook global hook, and return values ​​are abnormal is determined according to the internal source of write

1. The function named "clean_ field name" or "clean"

2. Data verification error, ValidationError can only throw an exception, because the capture anomalies in the source ValidationError

3. Data verification is successful, return data

Guess you like

Origin www.cnblogs.com/863652104kai/p/11454836.html