如何检查电子邮件已经在数据库中或不在Django中?

问题描述

我想在注册表格中添加一个功能,如果数据库中已经有电子邮件,而不是显示消息,即该电子邮件已经注册。 我正在尝试使用以下代码,但这无法正常工作

accounts / forms.py

from django.contrib.auth import get_user_model
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm


class UserCreateForm(UserCreationForm):

    # email = forms.EmailField()
    class Meta:
        fields = ["username","email","password1","password2"]
        model = get_user_model()
        
    def clean_email(self):
            email = self.cleaned_data.get('email')
            if email in User.objects.all():
                raise forms.ValidationError("This email is already register")
            return email
    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)
        self.fields['username'].label = 'Display Name'
        # self.fields['email'].label = 'Email Address'

解决方法

您以错误的方式运行验证,应该是

class UserCreateForm(UserCreationForm):
    # rest of your code

    def clean_email(self):
        email = self.cleaned_data["email"]
        if User.objects.filter(email__iexact=email).exists():
            raise forms.ValidationError("Only .edu email addresses allowed")
        return email
,

在您的UserCreateForm.clean_email中,您没有检查正确的方式。您正在通过此if email in User.objects.all()进行检查。这里的email不是User对象。 User.objects.all()返回queryset个对象中的一个User个对象。由于email不是User的实例,因此条件检查不成功。而是执行以下操作来检查提供的电子邮件是否已经存在用户

def clean_email(self):
    email = self.cleaned_data.get('email')
    if email.split('.')[-1] !=  'edu' :
        raise forms.ValidationError("Only .edu email addresses allowed")
    if User.objects.filter(email__iexact=email).exists():
        raise forms.ValidationError("User with that email already exists")
    return email

确保在email模型中将User设置为unique

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...