Key(email)=(macmusonda@gmail.com)already exists error in django

fnvucqvd  于 2023-06-07  发布在  Go
关注(0)|答案(1)|浏览(176)

我正在尝试在我的django电子商务Web应用程序中注册新用户。我使用的是custombased模型。但是每当我提交表单时,我的数据库显示用户已被保存,但随后出现此错误“重复的键值违反了唯一约束”account_account_email_key“详细信息:Key(email)=(macmusonda@gmail.com)already exists.”仍然出现。用户甚至可以登录。.我如何摆脱这个错误??
我的views.py

import email
from django.shortcuts import render, redirect
from django.contrib.auth import login, authenticate
from account.forms import RegistrationForm
from django.contrib import messages
from .models import Account


def registration(request):
    if request.method == "POST":
        form = RegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            first_name = request.POST['first_name']
            other_names =  request.POST['other_names']
            email =  request.POST['email']
            username = request.POST['username']
            raw_password =  request.POST['password1']
            phonenumber =  request.POST.get('phonenumber')
            Address_1 =  request.POST['Address_1']
            Address_2 =  request.POST['Address_2']
            user = Account.objects.create_user(first_name=first_name, other_names=other_names, email=email, username=username, password=raw_password, phonenumber=phonenumber, Address_1=Address_1, Address_2=Address_2)
            user.save()
            messages.success(request, ('Your account was successfully created!'))
            login(request, user)
            return redirect('home')
        else:
            messages.error(request, ('Invalid input.'))
    else:
        form = RegistrationForm()
    return render(request, 'account/register.html', {'form': form})

def login(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(request, username=username, password=password)

        try:
            user = Account.objects.get(username=username)
        except:
            messages.error(request, 'username does not exist')

        user = authenticate(request, username=username, password=password)

        if user is not None:
            login(request, user)
            return redirect('home')
        else:
            messages.error(request, 'Invalid Username Or Password')
    return render(request, 'account/login.html')

还有我的models.py

import email
from django.db import models
from django.conf import settings
from phonenumber_field.modelfields import PhoneNumberField
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.base_user import BaseUserManager

class MyAccountManager(BaseUserManager):
    def _create_user(self, email, username, password, first_name, other_names, phonenumber, Address_1, Address_2):
        if not email:
            raise ValueError("User must have an email")
        if not username:
            raise ValueError("User must have a username")

        user = self.model(
               email = self.normalize_email(email),
               username = username, password=password, first_name = first_name, other_names = other_names,
               phonenumber = phonenumber, Address_1 = Address_1, Address_2 = Address_2
            )   

        user.set_password(password)
        user.save(using=self._db)
        return user 

    def create_user(self, email, username, password, first_name=None, other_names=None, phonenumber=None, Address_1=None, Address_2=None):
        return self._create_user(email, username, password,first_name, other_names, phonenumber, Address_1, Address_2)

    def create_superuser(self, email, username, password):
        """
        Creates and saves a superuser with the given email, name and password.
        """
        user = self.create_user(email=email,
            username=username,
            password=password,
            
        )
        user.is_admin = True
        user.is_superuser = True
        user.is_staff = True
        user.save(using=self._db)
        return user

class Account(AbstractBaseUser, PermissionsMixin):
    first_name = models.CharField(verbose_name='first_name', max_length=60, null=True)
    other_names = models.CharField(verbose_name='other_names', max_length=200, null=True)
    phonenumber = PhoneNumberField(verbose_name='phonenumber', null=True)
    email = models.EmailField(verbose_name="email", max_length=60, unique=True)
    username = models.CharField(max_length=60, unique=True)
    Address_1 = models.CharField(max_length=60, blank=False, null=True)
    Address_2 = models.CharField(max_length=60, blank=False, null=True)
    date_joined = models.DateTimeField(verbose_name='date_joined', auto_now_add=True)
    last_login = models.DateTimeField(verbose_name='last_login', auto_now=True)
    is_admin = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']
    objects = MyAccountManager()

    def __str__(self):
        return self.username

    def has_perm(self, perm, obj=None):
        return self.is_admin

    def has_module_perms(self, app_label):
        return True

我真的不知道如何去这个错误。。需要一些解释,它来自哪里,以及如何摆脱它

3df52oht

3df52oht1#

试着用这个方法,它对我有效
类CustomUserManager(BaseUserManager):

def _create_user(self, email, password, **extra_fields):
    if not email:
        raise ValueError("Email field is required")

    email = self.normalize_email(email)
    user = self.model(email=email, **extra_fields)
    user.set_password(password)
    user.save()
    return user

def create_superuser(self, email, password, **extra_fields):
    extra_fields.setdefault('is_staff', True)
    extra_fields.setdefault('is_superuser', True)
    extra_fields.setdefault('is_active', True)
    extra_fields.setdefault('name', "admin")

    if extra_fields.get("is_staff") is not True:
        raise valueError("Superuser must have is_staff=True")

    if extra_fields.get("is_superuser") is not True:
        raise ValueError("Superuser must have is_superuser=True")

    return self._create_user(email, password, **extra_fields)

相关问题