簡體   English   中英

創建自定義超級用戶后無法登錄 django 管理面板

[英]Not able to login to django admin panel after creating custom super user

大家好,我盡力了,但我無法使用我的自定義用戶 model 登錄到 django 管理面板。我做了我能做的所有事情,我還對 email 和 rest 進行了身份驗證,但我仍然沒有能夠登錄到 django 管理面板,它一直在說:

請輸入正確的員工帳號email和密碼。 兩個地方都要注意大小寫。

我嘗試並檢查了我的密碼大概一百次了,但我仍然不讓我登錄。

有人可以幫我解決這個問題,這將是有史以來最大的幫助。 我已經被困在這里一個月了。

我已經粘貼了我在下面所做的所有代碼。

模型.py:

from django.db import models
import uuid
from django.utils import timezone
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager
from django.utils.translation import gettext_lazy as _

class CustomAccountManager(BaseUserManager):

    def create_user(self, first_name, last_name, phone_number, email, password, **other_fields):

        if not email:
            raise ValueError(_('You must provie an email address'))

        if not first_name:
            raise ValueError(_('You must provide a first name'))

        if not last_name:
            raise ValueError(_('You must provide a last name'))

        email = self.normalize_email(email)
        user = self.model(email=email, first_name=first_name, last_name=last_name, phone_number=phone_number, **other_fields)
        user.set_password(password)
        user.save()
        return user

    def create_superuser(self, email, first_name, last_name, phone_number, password, **other_fields):
        other_fields.setdefault('is_staff', True)
        other_fields.setdefault('is_superuser', True)
        other_fields.setdefault('is_active', True)

        if other_fields.get('is_staff') is not True:
            raise ValueError(_('Superuser must be assigned to is_staff=True'))

        if other_fields.get('is_active') is not True:
            raise ValueError(_('Superuser must be assigned to is_active=True'))

        if other_fields.get('is_superuser') is not True:
            raise ValueError(_('Superuser must be assigned to is_superuser=True'))

        return self.create_user(email, first_name, last_name, password, phone_number, **other_fields)

class NewUser(AbstractBaseUser, PermissionsMixin):
    first_name = models.CharField(max_length=200, null=True, blank=True)
    last_name = models.CharField(max_length=200, null=True, blank=True)
    email = models.EmailField(max_length=200, null=True, blank=True, unique=True)
    password = models.CharField(max_length=200,null=True, blank=True)
    confirm_password = models.CharField(max_length=200, null=True, blank=True)
    phone_number = models.CharField(max_length=10,null=True, blank=True)
    address = models.TextField(null=True, blank=True)
    pin_code = models.CharField(null=True, max_length=6, blank=True)
    region = models.CharField(null=True, max_length=200, blank=True)
    state = models.CharField(null=True, max_length=100, blank=True)
    start_date = models.DateField(default=timezone.now)
    is_staff = models.BooleanField(default=False)
    is_active = models.BooleanField(default=False)
    id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) 

    objects = CustomAccountManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['first_name', 'last_name', 'phone_number']

    def __str__(self):
        return self.first_name + ' ' + self.last_name

身份驗證.py:

from .models import NewUser
from django.contrib.auth.backends import BaseBackend

class EmailAuthBackend(BaseBackend):
    model = NewUser
    def authenticate(self, request = None, email=None, password=None):
        try:
            user = self.model.objects.get(email=email)
        except self.model.DoesNotExist:
            return None
        if self.model.check_password(password) and user is not None:
            return user

    def get_user(self, user_id):
        try:
            return self.model.objects.get(id=user_id)
        except self.model.DoesNotExist:
            return None

管理員.py:

from django.contrib import admin
from .models import NewUser

# Register your models here.

admin.site.register(NewUser)

設置.py:

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'user.apps.UserConfig',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'LavanderWoods.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'LavanderWoods.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

AUTH_USER_MODEL = 'user.NewUser'

AUTHENTICATION_BACKENDS = [
    'user.authentication.EmailAuthBackend',
    'django.contrib.auth.backends.ModelBackend',
]

這就是這個自定義用戶 model 所需的所有代碼。請有人幫助我受夠了這個,就像真的受夠了一樣。

你可以試試這個:

在模型.py 中:

from django.contrib.auth.models import (
    AbstractBaseUser,
    BaseUserManager,
    PermissionsMixin,
)

class UserManager(BaseUserManager):
    '''Manager for users.'''

    def create_user(self, email, password=None, **extra_fields):
        '''Create, save and return a new user.'''
        if not email:
            raise ValueError('User must have an email address.')
        user = self.model(email=self.normalize_email(email), **extra_fields)
        user.set_password(password)
        user.save(using=self._db)

        return user

    def create_superuser(self, email, password):
        '''Create and return a new superuser.'''
        user = self.create_user(email, password)
        user.is_staff = True
        user.is_superuser = True
        user.save(using=self._db)

        return user

class User(AbstractBaseUser, PermissionsMixin):
    '''User in the system.'''
    email = models.EmailField(max_length=255, unique=True)
    name = models.CharField(max_length=255)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)

    objects = UserManager()

    USERNAME_FIELD = 'email'

注意:這是基於 email 的登錄。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM