python - 如何检查电子邮件是否已在数据库中或不在 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'
解决方案
您以错误的方式运行验证,它应该是,
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
推荐阅读
- android - 如何使用 Kotlin 删除底部导航栏顶部的边框或线条?
- prolog - 在 prolog 中从文本文件中读取
- java - 从接口只创建一个 bean 实例
- javascript - “未知”类型上不存在属性“id/name/duration/calories”
- sockets - TCP 连接和客户端和服务器的不同缓冲区大小
- java - JavaFX AnimationTimer 没有正确停止
- jquery - 将调用的动态数量添加到 deferred.promise 队列
- c++ - getline(cin, input) 试图在一个字符串中存储多个单词。getline(cin, input) 在这种情况下不起作用
- java - java中的游程编码
- c# - 如何将我的 Angular 10 应用程序与 C#(包含 PostgreSQL 连接)连接?