python - 将 ValidationError 提升为字典时出错

标签 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.'})

再次输入现有电子邮件时,我在应用程序的调试屏幕上收到以下错误:

enter image description here

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

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

最佳答案

使用 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.'})

关于python - 将 ValidationError 提升为字典时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30575552/

相关文章:

python - 当任何类型可以有零个元素时,元素类型组合的解决方案

通过 WSGI 连接 Android Django

python - scikit-learn 线性回归的意外交叉验证分数

python - 通过坐标计算平面二维列表中项目位置的最短方法是什么?

python - 以django模型形式设置初始值

django-cities 数据导入不起作用

algorithm - 从 python 中的序列列表中提取特定对象

python - 必须以实例作为第一个参数调用未绑定(bind)方法 - python

python - 通过变量从列表中删除项目

python - PyQt Q线程 : Destroyed while thread is still running