form过滤代码:
class LoginForm(forms.Form): username = forms.CharField(max_length=20,min_length=3,label='用户名',error_messages={ 'required':'用户名不能为空!', 'invalid':'格式错误!', 'max_length':'用户名长度超限!', 'min_length':'用户名过短!' } ,widget=forms.widgets.TextInput(attrs={ 'class':'form-control','style':'width:300px'}) ) password = forms.CharField(max_length=18,min_length=3,label='密码',error_messages={ 'required':'密码不能为空!', 'invalid':'格式错误!', 'max_length':'密码长度超限!', 'min_length':'密码长度过短!', } ,widget=forms.widgets.PasswordInput(attrs={ 'class':'form-control','style':'width:300px'}) ) def clean_username(self): username = self.cleaned_data.get("username") # 错将这里的username写掉了一个字母 if username[0].isdigit(): self.add_error('username','用户名不能以数字开头!') return username def clean_password(self): password = self.cleaned_data.get("password") if password == '123': self.add_error('password','密码过于简单!') return password
视图函数:
def login(request): form_obj = LoginForm() if request.method == "POST": form_obj = LoginForm(request.POST) print(form_obj.clean_data)#结果:{'username': None, 'password': '1234',}
百思不得其解,虽然知道是哪里出了问题,但是就是找不出来,哎哎,
def clean_username(self): username = self.cleaned_data.get("username") # 错将这里的username写掉了一个字母 if username[0].isdigit(): self.add_error('username','用户名不能以数字开头!')
return username # 这里必须return 回去 不然clean_data里面的username的值就是None
这回长记性了,这里get错了,username拿到的就是个None啊,返回回去也是个None,擦泪~~~