MikeN
问问题
4971 次
2 回答
42
于 2009-02-17T15:17:58.860 回答
11
您可以在表单字段定义上执行此操作,而无需像这样引发表单级别 ValidationError:
class RegistrationForm(ModelForm):
...
### Django established methods
# form wide cleaning/validation
def clean_email(self):
""" prevent users from having same emails """
email = self.cleaned_data["email"]
try:
User.objects.get(email__iexact=email)
raise forms.ValidationError(
mark_safe(('A user with that email already exists, click this <a href="{0}">Password Reset</a> link'
' to recover your account.').format(urlresolvers.reverse('PasswordResetView')))
)
except User.DoesNotExist:
return email
...
### Additional fields
location = forms.RegexField(max_length=255,
regex=r"^[\w' -]+, [\w'-]+, [\w'-]+, [\w'-]+$", #ex 1 Mclure St, Kingston, Ontario, Canada
help_text="location, ex: Suite 212 - 1 Main St, Toronto, Ontario, Canada",
error_messages={
'invalid': mark_safe("Input format: <strong>suite - street</strong>, <strong>city</strong>, "
"<strong>province/state</strong>, <strong><u>country</u></strong>. Only letters, "
"numbers, and '-' allowed.")})
于 2013-07-09T20:26:50.817 回答