gpt4 book ai didi

Django 表单不调用 clean_

转载 作者:行者123 更新时间:2023-12-04 04:46:56 24 4
gpt4 key购买 nike

我正在尝试验证表单(它以前曾经工作过)。出于某种原因,我似乎无法在调用 form.is_valid() 时调用各种清理函数,例如 clean_username(self) 。

我知道还没有足够的检查(你看到它们正在 build 中;-)),但这是我的类(class):

  class LoginForm(forms.Form):
username = forms.CharField(max_length=30)
password = forms.CharField(max_length=30,widget=forms.PasswordInput)

def clean_password(self):
print "Cleaning password"
password = self.cleaned_data['password']
if password == u"":
raise forms.ValidationError("Password is blank.")
return password

def clean_username(self):
username = self.cleaned_data['username']
if len(username) < 4:
raise forms.ValidationError("Username is fewer than four charecters.")
return username


class RegistrationForm( LoginForm ):
confirm_password = forms.CharField(widget=forms.PasswordInput, max_length=30)
email = forms.EmailField()

def clean_confirm_password(self):
print "Cleaning confirm password"
clean_confirm_password = self.cleaned_data['confirm_password']
if clean_confirm_password == u"":
raise forms.ValidationError("Confirming password is blank.")
return clean_confirm_password

def clean(self):
print "Running clean on a registration form"
print self.cleaned_data.items()
password = self.cleaned_data['password']
confirm = self.cleaned_data['confirm_password']
if password != confirm:
raise forms.ValidationError('Passwords do not match.')
return self.cleaned_data

谢谢!

最佳答案

我在潜入 Django 后发现了错误的根源 forms.py 来源。

似乎如果一个字段留空,表单会在调用 field.clean() 后为该字段引发 ValidationError ,但它不会调用 clean_<fieldname> ,但它仍然调用该类的主要 clean 方法。为了处理使用这些空白字段的干净方法,您必须执行以下操作:

def clean(self):
try:
password = self.cleaned_data['password']
# etc
except KeyError:
raise ValidationError('The password field was blank.')

return self.cleaned_data

关于Django 表单不调用 clean_<fieldname>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1871746/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com