首页 > 解决方案 > 如何检查电子邮件是否已在数据库中或不在 django 中?

问题描述

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

帐户/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'

标签: pythondjangosqlitedjango-modelsdjango-forms

解决方案


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

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

推荐阅读