将ValidationError提升为字典时出错

时间:2015-06-01 14:01:15

标签: python django python-2.7 django-models django-forms

Django新手在这里。我试图在我的自定义表单中为电子邮件字段引发错误。我的forms.py有以下代码来验证电子邮件:

def clean_email(self):
    email = self.cleaned_data["email"]
        try:
            User._default_manager.get(email=email)
                except User.DoesNotExist:
                return email
        raise ValueError({'email':'Email already registered. 
                     Login to continue or use another email.'})

再次输入现有电子邮件时,我在app的调试屏幕上出现以下错误:

enter image description here

我在这里做错了什么?我正在关注此LINK

修改 将ValueError更改为ValidationError时出现此错误当field参数包含多个字段的错误时,参数None必须为error

3 个答案:

答案 0 :(得分:3)

你不应该提出ValueError,你应该提出forms.ValidationError

答案 1 :(得分:2)

使用raise ValidationError代替raise ValueError

def clean(self):
    email = self.cleaned_data["email"]
    try:
        User._default_manager.get(email=email)
    except User.DoesNotExist:
        return self.cleaned_data
    raise ValidationError({'email':'Email already registered. Login to continue or use another email.'})

答案 2 :(得分:1)

使用clean_时,请勿指定字典。在该方法中引发的任何ValidationError都会自动与该字段关联。

def clean_email(self):
    email = self.cleaned_data["email"]
    try:
        User._default_manager.get(email=email)
    except User.DoesNotExist:
        return email
    raise ValidationError('Email already registered. 
                 Login to continue or use another email.')