При ссылке на модели из моего основного приложения 'core_hr' в моем приложении пользовательской модели, где я переопределил AbstractBaseUser для определения новой пользовательской модели, я получал сообщение об ошибке
Пока не попытался импортировать модели из другого django приложение в мое переопределенное пользовательское приложение пользовательской модели Я никогда не видел эту ошибку. Все мои приложения находятся в установленных приложениях.
"AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL
django .core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL относится к модели 'users.Employee', которая не была установлена
models.py
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
from django.utils.translation import gettext_lazy as _
from django.utils import timezone
# ---->from core_hr.models import Passport, RegistryOfStay <-----
from .managers import CustomUserManager
from ####.storage_backends import PublicMediaStorage, PrivateMediaStorage
from django.core.validators import RegexValidator
name_validator = RegexValidator(r'^[a-z A-Z]*$', 'Only Alphabetic characters allowed')
class Employee(AbstractBaseUser, PermissionsMixin):
employment_statuses = (
('ap','Applicant'),
('trial', 'Initial Training'),
('em', 'Employed'),
('ps','Pause')
)
genders = (('M', 'male'),('F', 'female'))
# core information
full_name = models.CharField(_('Surname, Given Names as on passport'), validators=[name_validator], max_length=25, blank=False, null=True)
#employment data
gender = models.CharField(max_length=10, choices=genders)
employee_id_number = models.CharField(_('employee id number'), max_length=20, null=True)
# activity Status
employment_status = models.CharField(choices=employment_statuses, max_length=30)
employment_status_note = models.TextField(max_length=500)
# contact information
phone_number = models.CharField(max_length=14, unique=True)
email = models.EmailField(_(' email address'), unique=True)
personal_email = models.EmailField(_('Personal Email Address'), unique=True)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
date_joined = models.DateTimeField(_('date joined'), auto_now_add=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = CustomUserManager()
def get_contact_info(self):
try:
return f"{self.phone_number}, {self.email}, {self.personal_email}"
except:
return "Error during retrieval of contact info, perhaps it isn't complete"
def passport_complete(self):
from core_hr.models import Passport
try:
passport = Passport.objects.get(owner=self)
return passport.data_complete
except ObjectDoesNotExist:
return ["Couldn't query passport, perhaps it was not created?", False]
def ros_form_complete(self):
from core_hr.models import RegistryOfStay
try:
ros_form = RegistryOfStay.objects.get(owner=self)
return ros_form.data_complete
except ObjectDoesNotExist:
return ["Couldn't query Registry of stay, perhaps it was not created", False]
pass
@property
def core_documents_complete(self):
completion_statuses = [self.passport_complete(), self.ros_form_complete()]
return False if False in completion_statuses else True
def first_name(self):
try:
return str(self.full_name.split()[1])
except:
pass
def middle_name(self):
try:
return str(self.full_name.split()[2])
except:
pass
def last_name(self):
try:
return str(self.full_name.split()[0])
except:
pass
def __str__(self):
return f"{self.full_name} {self.email}"
После прочтения: AUTH_USER_MODEL относится к модели .. которая не была установлена и создана модели AbstractUser, не способные войти
Я решил прокомментировать:
---->from core_hr.models import Passport, RegistryOfStay <-----
и добавление импорта области действия функции класса модели в функции полезности моих моделей (не уверен, что это отличная идея?) PEP8 рекомендует не - >> импорт на уровне модуля или на уровне функций? (но ответ подразумевает, что это несколько ситуативно)
from core_hr.models import Passport
try:
passport = Passport.objects.get(owner=self)
return passport.data_complete
except ObjectDoesNotExist:
return ["Couldn't query passport, perhaps it was not created?", False]
И это решило проблему. Я пойму sh, чтобы понять, почему импорт на уровне функций устранил проблему.
Я действительно просто обеспокоен непредвиденными побочными эффектами в дальнейшем в проекте, а также тем, является ли это наилучшей практикой или нет. №.
Редактировать:
settings.py:
"""
Django settings for docker_files.
Generated by 'django-admin startproject' using Django 3.0.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
#!/usr/bin/env python
import os
# Build paths inside the docker_files like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR, '/templates')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
#
# STATIC_URL = '/static/'
# STATIC_ROOT = os.path.join(BASE_DIR, 'static')
#
# static files settings
STATIC_URL = '/staticfiles/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = (os.path.join(BASE_DIR,'static'),)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
AWS_DEFAULT_ACL = 'public-read'
USE_S3 = os.getenv('USE_S3') == 'TRUE'
if USE_S3:
AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME = os.getenv('AWS_STORAGE_BUCKET_NAME')
AWS_DEFAULT_ACL = 'public-read'
AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com'
AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'}
# s3 static settings
AWS_LOCATION = 'static'
# STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/'
# STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
# s3 media settings
PUBLIC_MEDIA_LOCATION = 'media'
MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{PUBLIC_MEDIA_LOCATION}/'
DEFAULT_FILE_STORAGE = '#####.storage_backends.PublicMediaStorage'
PRIVATE_MEDIA_LOCATION = 'private'
PRIVATE_FILE_STORAGE = '#####.storage_backends.PrivateMediaStorage'
else:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get('SECRET_KEY','change me to a real key')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG=True
if os.environ.get('DEV'):
DEBUG = True
ALLOWED_HOSTS = ['*']
else:
ALLOWED_HOSTS=['*']
INSTALLED_APPS = [
#'whitenoise.runserver_nostatic',
#'livereload',
'users',
'django.contrib.contenttypes',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# Local
# 'debug_toolbar'
'######',
'core_hr',
'schedules',
'org',
# extensions
'django_countries',
'django_nose',
'storages',
'django_extensions'
]
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
NOSE_ARGS = [
'--with-cover',
'--cover-package=core_hr',
'--cover-package=####',
]
MIDDLEWARE = [
#'livereload.middleware.LiveReloadScript',
#'whitenoise.middleware.WhiteNoiseMiddleware',
'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 = '####.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [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 = '####.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
if os.environ.get('PROD'):
DATABASES = {
"default": {
"ENGINE": os.environ.get("SQL_ENGINE"),
"NAME": os.environ.get("SQL_DATABASE"),
"USER": os.environ.get("SQL_USER", "user"),
"PASSWORD": os.environ.get("SQL_PASSWORD", "password"),
"HOST": os.environ.get("SQL_HOST", "localhost"),
"PORT": os.environ.get("SQL_PORT", "5432"),
}
}
else:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'devdb.sqlite3'),
}
}
# CUSTOM USER MODEL
AUTH_USER_MODEL = 'users.Employee'
# Password validation
# https://docs.djangoproject.com/en/3.0/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.0/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.0/howto/static-files/