当前在注册过程中,当用户输入现有用户名和电子邮件时,系统会通知该用户名已存在于数据库中。当用户输入其他用户名但存在一封电子邮件时,将在db中成功创建用户。 所以我想验证数据库中是否存在电子邮件。因此,我创建了以下内容,但不幸的是,它无法按预期工作(如果存在相同的电子邮件,则会创建用户)。
forms.py文件
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django import forms
class SignupForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
def clean_email(self):
# Get the email
email = self.cleaned_data.get('email')
if User.objects.filter(email__iexact=email).exists():
raise forms.ValidationError("User with that email already exists")
return email
views.py文件
from django.shortcuts import render
from django.contrib.messages.views import SuccessMessageMixin
from django.views import generic
from django.contrib.auth.forms import UserCreationForm
from django.urls import reverse_lazy
from .forms import SignupForm
class UserRegisterView(SuccessMessageMixin, generic.CreateView):
form_class = SignupForm
template_name = 'registration/register.html'
success_url = reverse_lazy('login')
success_message = "Hello %(username)s! Your account has been created"
谢谢您的时间。