为什么在django自定义用户模型后进不去admin界面?
Why can't I enter the admin interface in django after customizing the user model?
所以我一直在尝试自定义我的django程序的用户模型,我的model.py看起来像这样
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 customer_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 customer(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 = customer_base_manager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username', 'firstname', 'lastname', 'contact']
def __str__(self):
return self.username
它在 makemigrations
和 migrate
之后工作 我也可以在 createsuperuser
之后在这里创建超级用户
如你所见,我实际上打印了输入的密码,所以我可以真正检查它
唯一的问题是,当我实际尝试这些凭据时,我实际上并没有进入管理界面我并没有真正登录管理界面
我现在真的很想投降 谁能告诉我发生了什么事吗?这是我的 settings.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.customer'
为什么不启动 shell 并检索您的用户实例:
c = customer.objects.get(email="somest...")
然后检查所有属性。我觉得
other_fields.setdefault('is_active', False)
这里有问题。用户需要处于活动状态才能获得访问权限。
所以我一直在尝试自定义我的django程序的用户模型,我的model.py看起来像这样
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 customer_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 customer(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 = customer_base_manager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username', 'firstname', 'lastname', 'contact']
def __str__(self):
return self.username
它在 makemigrations
和 migrate
之后工作 我也可以在 createsuperuser
如你所见,我实际上打印了输入的密码,所以我可以真正检查它
唯一的问题是,当我实际尝试这些凭据时,我实际上并没有进入管理界面我并没有真正登录管理界面
我现在真的很想投降 谁能告诉我发生了什么事吗?这是我的 settings.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.customer'
为什么不启动 shell 并检索您的用户实例:
c = customer.objects.get(email="somest...")
然后检查所有属性。我觉得
other_fields.setdefault('is_active', False)
这里有问题。用户需要处于活动状态才能获得访问权限。