Jadi saya telah mencoba untuk menyesuaikan model pengguna dari program Django saya, model.py saya terlihat seperti ini

from django.db import models
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager
from django.core.validators import MaxValueValidator, MinValueValidator
from django.utils.translation import gettext_lazy as _
from django.utils import timezone
# Create your models here.


class costumer_base_manager(BaseUserManager):
    def create_user(self, email, username,firstname, lastname, password, contact, **other_fields):
        if not email:
            raise ValueError("Please provide email")
        email = self.normalize_email(email)
        user  = self.model(email=email, username=username, firstname=firstname, lastname=lastname, password=password,contact=contact, **other_fields)
        print(password)
        user.set_password(password)
        print(password)
        user.save()
        return user
    def create_superuser(self, email, username,firstname, lastname, password, contact, **other_fields):
        other_fields.setdefault('is_staff', True)
        other_fields.setdefault('is_superuser', True)
        other_fields.setdefault('is_active', False)
        if other_fields.get('is_staff') is not True:
            raise ValueError('Superuser must assign is_staff = True')
        
        return self.create_user(email, username, firstname, lastname, password, contact, **other_fields)



class costumer(AbstractBaseUser, PermissionsMixin):
    email           = models.EmailField(_("email"),unique=True, blank=False)
    username       = models.CharField(max_length=100, unique=True)
    firstname       = models.CharField(max_length=100, blank=False)
    lastname       = models.CharField(max_length=120, blank=False)
    start_date      = models.DateTimeField(default=timezone.now)
    about           = models.TextField(_("about me"), max_length=500, blank=True)
    investing_style = models.PositiveIntegerField(default=0,validators=[MinValueValidator(0), MaxValueValidator(3)])
    contact         = models.PositiveIntegerField(default=0,validators=[MinValueValidator(9000000001), MaxValueValidator(9999999999)])
    is_active       = models.BooleanField(default=False)
    is_staff        = models.BooleanField(default=False)

    objects = costumer_base_manager()
    USERNAME_FIELD  = 'email'
    REQUIRED_FIELDS = ['username', 'firstname', 'lastname', 'contact']

    def __str__(self):
        return self.username

Dan itu berhasil setelah makemigrations dan migrate Saya juga dapat membuat pengguna super di sini setelah createsuperuser

As you can see I actually printed the inputted password so I can really check it

Seperti yang Anda lihat, saya benar-benar mencetak kata sandi yang dimasukkan sehingga saya benar-benar dapat memeriksanya

Satu-satunya hal adalah ketika saya benar-benar mencoba kredensial itu, saya tidak benar-benar memasuki antarmuka admin, saya tidak benar-benar masuk ke antarmuka admin

enter image description here

enter image description here

Saya benar-benar ingin menyerah sekarang dapatkah seseorang memberi tahu saya apa yang terjadi? Ini pengaturan saya.py

"""
Django settings for finbot project.

Generated by 'django-admin startproject' using Django 3.2.

For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
import os
from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# print("hey => ",BASE_DIR)

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecurey-^kl(js@#3vv-!o&@q^%rget%oh2=^#u0d5b-y*i()@yo-kew3h'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'products',
    'dashboard',
    'pages',
    'users',
    # third party
]

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 = 'finbot.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(BASE_DIR, "dashboard/templates"),
            os.path.join(BASE_DIR, "products/templates"),
            os.path.join(BASE_DIR, "templates")],
        '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 = 'finbot.wsgi.application'


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

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


# Password validation
# https://docs.djangoproject.com/en/3.2/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/3.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


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

STATIC_URL = '/static/'
MEDIA_URL = '/images/'
STATICFILES_DIRS =[
    os.path.join(BASE_DIR,'static')
]

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

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
AUTH_USER_MODEL = 'users.costumer'
0
super_newb 23 April 2021, 09:27

1 menjawab

Jawaban Terbaik

Mengapa tidak menjalankan shell dan mengambil instance pengguna Anda:

C = costumer.objects.get(email="terbaik...")

Kemudian periksa semua atribut. Saya merasa other_fields.setdefault('is_active', False) adalah masalah di sini. Pengguna harus aktif untuk mendapatkan akses.

1
somecallitblues 23 April 2021, 06:32