from django.core.exceptions import ValidationError from app01 import models from app01.utils.bootstrap import BootStrapModelForm from django import forms import re class UserModelForm(BootStrapModelForm): # name = forms.CharField(max_length=3,label="用户名") name = forms.CharField(max_length=3, label="用户名") password = forms.CharField(min_length=5, max_length=14, label="密码") class Meta: model = models.UserInfo fields = ["name", "password", "age", "account", "create_time", "depart", "gender"] # widgets={ # "name":forms.TextInput(attrs={"class":"form-control"}) # } # def __init__(self, *args, **kwargs): # super().__init__(self, **kwargs) # # for name, field in self.fields.item(): # print(name,field) def clean_name(self): name = self.cleaned_data['name'] if not re.match(r'^[\u4e00-\u9fa5]{1,3}$', name): raise forms.ValidationError("用户名必须为1-3个中文字符") return name def clean_password(self): password = self.cleaned_data.get('password') # 定义密码中必须包含的正则表达式 has_digit = re.compile(r'\d') has_uppercase = re.compile(r'[A-Z]') has_lowercase = re.compile(r'[a-z]') has_special_char = re.compile(r'[!@#$%^&*(),.?":{}|<>]') # 检查密码是否至少包含一个数字、一个大写字母或者一个小写字母和一个特殊字符 if not (has_digit.search(password) and (has_uppercase.search(password) or has_lowercase.search(password)) and has_special_char.search(password)): raise ValidationError("密码必须至少包含一个大小写字母、一个数字和一个特殊字符。") # 如果以上条件都满足,返回密码值 return password