我有一个非常简单的表单:
from django import forms
class InitialSignupForm(forms.Form):
email = forms.EmailField()
password = forms.CharField(max_length=255, widget = forms.PasswordInput)
password_repeat = forms.CharField(max_length=255, widget = forms.PasswordInput)
def clean_message(self):
email = self.clean_data.get('email', '')
password = self.clean_data.get('password', '')
password_repeat = self.clean_data.get('password_repeat', '')
try:
User.objects.get(email_address = email)
raise forms.ValidationError("Email taken.")
except User.DoesNotExist:
pass
if password != password_repeat:
raise forms.ValidationError("The passwords don't match.")这就是自定义表单验证的方式吗?我需要在email上评估当前没有使用该电子邮件地址的用户。我还需要评估password和password_repeat的匹配度。我该怎么做呢?
发布于 2011-10-31 08:44:09
要单独验证单个字段,可以在表单中使用clean_FIELDNAME()方法,因此对于电子邮件:
def clean_email(self):
email = self.cleaned_data['email']
if User.objects.filter(email=email).exists():
raise ValidationError("Email already exists")
return email然后,对于相互依赖的相互依赖的字段,您可以覆盖表单clean()方法,该方法在所有字段(如上面的email )单独验证后运行:
def clean(self):
form_data = self.cleaned_data
if form_data['password'] != form_data['password_repeat']:
self._errors["password"] = ["Password do not match"] # Will raise a error message
del form_data['password']
return form_data我不确定您从哪里获得clean_message(),但它看起来像是为表单中不存在的message字段创建的验证方法。
请通读本文以了解更多详细信息:
https://stackoverflow.com/questions/7948750
复制相似问题