Hello Pros
I had a project all of a sudden I started seeing this error
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
i tried fixing it i failed miserably using all stack overflow i came across and django forum. So i started a new project, to see where I got it wrong, a very fresh project but as soon as i added in custom user model, the error wouldn’t allow me even make migrations or migrate
note: this is the only file i have added besides adding in the settings:
"""
Database models
"""
from django.db import models
from django.contrib.auth.models import(
AbstractBaseUser,
BaseUserManager,
PermissionsMixin,
)
from django.core.mail import send_mail
from django.template.loader import render_to_string
from django.utils import timezone
class UserManager(BaseUserManager, PermissionsMixin):
""" minimum fields for all users"""
def create_user(
self,
email,
telephone,
username,
first_name,
last_name,
password=None,
**extra_fields):
if not email:
raise ValueError('You need to provide an email address')
if not telephone:
raise ValueError('You need to provide a telephone')
if not username:
raise ValueError('You need to set a username')
""" calling the model this manager is responsible for with self.model."""
user = self.model(
email= self.normalize_email(email),
telephone =telephone,
username = username,
first_name = first_name,
last_name = last_name,
**extra_fields
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(
self,
email,
username,
first_name,
last_name,
password,
telephone,
**extra_fields):
""" calling the create_user method """
user =self.create_user(
email=self.normalize_email(email),
username=username,
password=password,
first_name=first_name,
last_name=last_name,
telephone=telephone,
**extra_fields
)
user.is_admin = True
user.is_active = True
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)
username = models.CharField(max_length=50, unique=True)
telephone = models.CharField(max_length=20, unique=True)
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
families = models.ManyToManyField('self')
""" required fields """
date_joined = models.DateTimeField(auto_now= True)
last_login = models.DateTimeField(auto_now= True)
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_superadmin = models.BooleanField(default=False)
is_email_verified = models.BooleanField(default=False)
id_telephone_verified = models.IntegerField(default=False)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username', 'first_name', 'last_name', 'telephone']
and the setting file is here
"""
Django settings for mascodlionheart project.
Generated by 'django-admin startproject' using Django 4.2.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/ref/settings/
"""
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-ep1+@q8hhpw%&r0mv1280xr5z2^w#1ro*-_%flx=z2jr_ydq(*'
# 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',
'authapp',
'coreapp'
]
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 = 'mascodlionheart.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['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 = 'mascodlionheart.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.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/4.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
AUTH_USER_MODEL = 'authapp.User'
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/
STATIC_URL = 'static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
the full error:
(venv) Mbisas-MacBook-Pro:masco jc$ python manage.py migrate
Traceback (most recent call last):
File "manage.py", line 22, in <module>
main()
File "manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/Users/jc/Desktop/masco/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line
utility.execute()
File "/Users/jc/Desktop/masco/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 416, in execute
django.setup()
File "/Users/jc/Desktop/masco/venv/lib/python3.8/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Users/jc/Desktop/masco/venv/lib/python3.8/site-packages/django/apps/registry.py", line 116, in populate
app_config.import_models()
File "/Users/jc/Desktop/masco/venv/lib/python3.8/site-packages/django/apps/config.py", line 269, in import_models
self.models_module = import_module(models_module_name)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/Users/jc/Desktop/masco/authapp/models.py", line 20, in <module>
class User(AbstractBaseUser, PermissionsMixin):
File "/Users/jc/Desktop/masco/venv/lib/python3.8/site-packages/django/db/models/base.py", line 365, in __new__
new_class._prepare()
File "/Users/jc/Desktop/masco/venv/lib/python3.8/site-packages/django/db/models/base.py", line 411, in _prepare
if not opts.managers:
File "/Users/jc/Desktop/masco/venv/lib/python3.8/site-packages/django/utils/functional.py", line 57, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/Users/jc/Desktop/masco/venv/lib/python3.8/site-packages/django/db/models/options.py", line 453, in managers
manager = copy.copy(manager)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/copy.py", line 102, in copy
return _reconstruct(x, None, *rv)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/copy.py", line 263, in _reconstruct
y = func(*args)
File "/Users/jc/Desktop/masco/venv/lib/python3.8/site-packages/django/db/models/base.py", line 2524, in model_unpickle
model = apps.get_model(*model_id)
File "/Users/jc/Desktop/masco/venv/lib/python3.8/site-packages/django/apps/registry.py", line 201, in get_model
self.check_models_ready()
File "/Users/jc/Desktop/masco/venv/lib/python3.8/site-packages/django/apps/registry.py", line 143, in check_models_ready
raise AppRegistryNotReady("Models aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.