registers same email which is already注册Django登录注册项目

lnlaulya  于 2023-10-21  发布在  Go
关注(0)|答案(2)|浏览(89)

我有一个Django项目的登录和注册,当一个新用户输入已经注册的相同用户名,但接受已经注册的电子邮件时,它会出错,如果已经注册了,如何避免电子邮件???有人能在这个问题上提供帮助吗?
我正在使用CRUD和登录注册在XNUMX项目。
My views.py code

def signup_page(request):
    # try:
        if request.method == 'POST':
           
            uname = request.POST.get('username')
            email = request.POST.get('email')
            pass2 = request.POST.get('password2')
            pass1 = request.POST.get('password1')
            if pass1 != pass2:
                return HttpResponse("Your password and confirm password are not Same!!")
            else:
                my_user = User.objects.create_user(uname,email,pass1)
                my_user.save()
                messages.info(request,"Signup is Succesfully")
                return redirect(reverse('login_page'));   
        return render (request,'registartion.html')
    # except Exception as e:
    #     raise ValueError("Account With this Username or Email is already registered")

def login_page(request):
    try:
        if request.method == 'POST':
            username = request.POST.get('username')
            pass1 = request.POST.get('pass')
            user = authenticate(request,username=username,password=pass1)
            if user is not None:
                login(request,user)
                messages.add_message(request,messages.INFO,"Succesfully Login")
                return redirect(reverse('dashboard_page'))
            else:
                return HttpResponse ("INCORRECT USERNAME OR PASSWORD")

        return render (request,'login.html')
    except Exception as e:
        raise ValueError("Incorrect Username Or Password !!!")

MY MODELS.PY

class Members(models.Model):
    GENDER_CHOICEs =(
    ('Male','Male'),
    ('Female','Female')
    )
    user = models.ForeignKey(User,on_delete=models.CASCADE)
    name = models.CharField(max_length=20,null=True,blank=False)
    email = models.EmailField(null=True,blank=False,unique=True)
    phone = models.CharField(null=True,blank=False,max_length=10)
    gender = models.CharField(choices=GENDER_CHOICEs, max_length=10)
    role = models.CharField(max_length=10)
    is_deleted = models.BooleanField(default=False)

    def __str__(self):
        return f'{self.name} {self.email} {self.role}'

我想如果一个用户的电子邮件已经注册,它会给予一个消息,电子邮件已经注册。

jdzmm42g

jdzmm42g1#

为了防止用户使用已经在Django项目中注册的电子邮件进行注册,您可以使用Django内置的身份验证和用户模型。以下是如何在www.example.com中修改注册视图views.py以检查重复的电子邮件并在电子邮件已注册时提供消息:

from django.contrib.auth import authenticate, login
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.shortcuts import render, redirect
from django.contrib import messages

def signup_page(request):
    if request.method == 'POST':
        uname = request.POST.get('username')
        email = request.POST.get('email')
        pass2 = request.POST.get('password2')
        pass1 = request.POST.get('password1')

        if pass1 != pass2:
            return HttpResponse("Your password and confirm password are not the same!!")
        else:
            if User.objects.filter(email=email).exists():
                messages.error(request, "This email is already registered.")
                return redirect(reverse('signup_page'))
            else:
                my_user = User.objects.create_user(uname, email, pass1)
                my_user.save()
                messages.success(request, "Signup is successfully")
                return redirect(reverse('login_page'))

    return render(request, 'registartion.html')

在更新后的代码中,我们首先使用User.objects.filter(email=email).exists()检查User模型中是否已经存在具有所提供电子邮件的用户。如果通过提供的电子邮件找到现有用户,我们将使用messages.error显示错误消息,并将用户重定向回注册页面。否则,用户将照常注册。
确保在Django项目的设置中正确设置了消息框架。
此代码将确保用户无法使用已注册的电子邮件进行注册,并且他们将收到一条消息,通知他们此问题。

sulc1iza

sulc1iza2#

您可以使用以下方法:

class Members(forms.Form):
    // other fields
    email = forms.EmailField()
    // other fields

    def clean_email(self):
        email = self.cleaned_data.get('email')
        if User.objects.filter(email=email).exists():
            raise forms.ValidationError("Email is already registered.")
        return email

相关问题