希望您一切都好。 从几个小时前开始,我在扩展Django的“用户”模型时出错,目的是为不同的用户添加一些字段。
要扩展模型,我依靠两个主要来源:
Github上的Django存储库-https://github.com/django/django/blob/master/django/contrib/auth/models.py
和来自博客的-simpleisbetterthancomplex-https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html#abstractbaseuser
Django版本= 2.1
在运行命令- python manage.py makemigrations 时,出现以下错误:
“ AUTH_USER_MODEL指的是尚未安装的模型'%s'”%设置。AUTH_USER_MODEL django.core.exceptions.ImproperlyConfigured:AUTH_USER_MODEL引用具有以下特征的模型'core.User' 尚未安装
要在settings.py中定义时-AUTH_USER_MODEL ='core.User'
是的,我有一个名为“ core”的应用程序,该应用程序已经在INSTALLED_APPS中
settings.py
import os
from decouple import config
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config('SECRET_KEY')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = config('DEBUG', cast=bool)
ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=lambda v: [s.strip() for s in v.split(',')])
# Application definition
DJANGO_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
THIRD_PARTY_APPS = [
'rest_framework',
]
LOCAL_APPS = [
'core',
'users',
'company',
]
INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS
# custome user model
AUTH_USER_MODEL = 'core.User'
# Argon2 password hash
PASSWORD_HASHERS = [
'django.contrib.auth.hashers.Argon2PasswordHasher',
'django.contrib.auth.hashers.PBKDF2PasswordHasher',
'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
]
.......
core / models.py
from __future__ import unicode_literals
from django.db import models
from django.core.mail import send_mail
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.base_user import AbstractBaseUser
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from .managers import UserManager
from .validators import UnicodeUsernameValidator
# Create your models here.
class User(AbstractBaseUser, PermissionsMixin):
"""
An abstract base class implementing a fully featured User model with
admin-compilant permissions
username and password are required, other fields are optional.
"""
username_validator = UnicodeUsernameValidator()
username = models.CharField(
_('Username'),
max_length=150,
unique=True,
help_text=_('Required: 150 Characters or fewer. Letters, digits and @/./+/-/_ only.'),
validators=[username_validator],
error_messages={
'unique': _('A user with that username already exists.')
},
)
email = models.EmailField(_('Email Address'), unique=True)
first_name = models.CharField(_('First name'), max_length=50, blank=True)
last_name = models.CharField(_('Last name'), max_length=60, blank=True)
is_staff = models.BooleanField(
_('Staff stauts'),
default=False,
help_text=_('Designates whether the user can log into this admin site.'),
)
is_active = models.BooleanField(
_('Active'),
default=False,
help_text=_(
'Designates whether this user should be treaged as active'
'unselect this instead of deleting accounts'
),
)
is_company = models.BooleanField(_('User company permissions'), default=False)
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
objects = UserManager()
EMAIL_FIELD = 'email'
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['email', 'username']
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')
abstract = True
def clean(self):
super().clean()
self.email = self.__class__.objects.normalize_email(self.email)
def get_full_name(self):
"""
Return the first_name plus the last_name, with a space in between
"""
full_name = '%s %s' %(self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
"""
Return the short name for the user
"""
return self.first_name
def email_user(self, subject, message, from_email=None, **kwargs):
"""
Send an email to this user
"""
send_mail(subject, message, from_email, [self.email], **kwargs)
代码中的ident很好,但是这里不是哈哈
core / apps.py
from django.apps import AppConfig
class CoreConfig(AppConfig):
name = 'core'
答案 0 :(得分:0)
好吧,最后我得到了答案,在我的类User ....中,我们需要在元代码中删除 abstract = True ,然后一切正常!
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')
abstract = True
到
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')