ModuleNotFoundError at /api/v1/account/users/1/
I have a django rest framework project with this kind of treeroot
in the accounts model I have a User model like bellow :
class User(AbstractUser):
phone_number = models.CharField(max_length=11, unique=True)
then I have a simple serializer and ModelViewSet for this model
the apps.py in accounts is as bellow :
from django.apps import AppConfig
class AccountsConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'api.accounts'
and in the api directory apps.py is like this :
from django.apps import AppConfig
class ApiConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'api'
and at the end this is my settings.py
"""
Django settings for listings project.
Generated by 'django-admin startproject' using Django 3.2.4.
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 environ
import os
from pathlib import Path
# 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/3.2/howto/deployment/checklist/
env = environ.Env()
DEBUG = True
BASE_URL_V1 = 'api/v1/'
# reading the EVN file
environ.Env.read_env(BASE_DIR.__str__() + '/../.env')
# Raises django's ImproperlyConfigured exception if SECRET_KEY not in os.environ
SECRET_KEY = env('SECRET_KEY')
AUTH_USER_MODEL = "accounts.User"
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'drf_spectacular',
'rest_framework',
'django_filters',
'api',
'api.books',
'api.accounts'
]
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 = 'config.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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 = 'config.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
POSTGRES_USER = env('POSTGRES_USER')
POSTGRES_NAME = env('POSTGRES_NAME')
POSTGRES_PASSWORD = env('POSTGRES_PASSWORD')
POSTGRES_HOST = env('POSTGRES_HOST')
POSTGRES_PORT = env('POSTGRES_PORT')
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': POSTGRES_NAME,
'USER': POSTGRES_USER,
'PASSWORD': POSTGRES_PASSWORD,
'HOST': POSTGRES_HOST,
'PORT': POSTGRES_PORT,
},
}
# 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/'
STATIC_ROOT = 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'
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.AllowAny'
],
'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema',
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework_simplejwt.authentication.JWTAuthentication',
)
}
# Logging configuration
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': '{asctime} {levelname} {filename} {funcName} {lineno} {message}',
'style': '{',
},
'simple': {
'format': '{asctime} {levelname} - {message}',
'style': '{',
},
},
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse',
},
'require_debug_true': {
'()': 'django.utils.log.RequireDebugTrue',
},
},
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'filters': ['require_debug_true'],
'formatter': 'simple',
},
'log_file': {
'level': 'DEBUG',
'class': 'logging.handlers.RotatingFileHandler',
'filename': 'api.log',
'maxBytes': 1024 * 1024 * 5, # 5 mb
'backupCount': 5,
'formatter': 'verbose',
},
'error_file': {
'level': 'ERROR',
'class': 'logging.handlers.RotatingFileHandler',
'filename': 'api_error.log',
'maxBytes': 1024 * 1024 * 5, # 5 mb
'backupCount': 5,
'formatter': 'verbose',
},
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler',
'filters': ['require_debug_false'],
'formatter': 'verbose',
},
},
'loggers': {
'ketab_api': {
'handlers': ['console', 'log_file', 'error_file', 'mail_admins'],
'level': 'DEBUG',
},
'django.request': {
'handlers': ['mail_admins', 'error_file'],
'level': 'ERROR',
'propagate': False,
},
},
}
SPECTACULAR_SETTINGS = {
'TITLE': 'Book',
'DESCRIPTION': 'Documentation of API endpoints of Book project',
'VERSION': '1.0.0',
"SCHEMA_PATH_PREFIX": "/api/v1/",
'COMPONENT_SPLIT_REQUEST': True
}
when I want to call this api via get :
/api/v1/account/users/
it gives me the bellow error :
ModuleNotFoundError at /api/v1/account/users/1/
No module named 'accounts'
Request Method: GET
Request URL: http://127.0.0.1:8000/api/v1/account/users/1/
Django Version: 3.2.25
Exception Type: ModuleNotFoundError
Exception Value:
No module named 'accounts'
Exception Location: <frozen importlib._bootstrap>, line 973, in _find_and_load_unlocked
Python Executable: /usr/local/bin/python3
Python Version: 3.8.20
Python Path:
['/opt/project',
'/opt/project',
'/opt/.pycharm_helpers/pycharm_display',
'/usr/local/lib/python38.zip',
'/usr/local/lib/python3.8',
'/usr/local/lib/python3.8/lib-dynload',
'/usr/local/lib/python3.8/site-packages',
'/opt/.pycharm_helpers/pycharm_matplotlib_backend']
Server time: Thu, 16 Jan 2025 05:29:15 +0000
and the TraceBack info is like this :
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/api/v1/account/users/1/
Django Version: 3.2.25
Python Version: 3.8.20
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'drf_spectacular',
'rest_framework',
'django_filters',
'api',
'api.books',
'api.accounts']
Installed 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']
Traceback (most recent call last):
File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/rest_framework/viewsets.py", line 125, in view
return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
raise exc
File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/rest_framework/mixins.py", line 55, in retrieve
serializer = self.get_serializer(instance)
File "/usr/local/lib/python3.8/site-packages/rest_framework/generics.py", line 108, in get_serializer
serializer_class = self.get_serializer_class()
File "/opt/project/api/util/ViewSetUtil.py", line 21, in get_serializer_class
module = importlib.import_module(f"{current_model._meta.app_label}.serializers")
File "/usr/local/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
<source code not available>
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
<source code not available>
File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked
<source code not available>
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
<source code not available>
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
<source code not available>
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
<source code not available>
File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked
<source code not available>
Exception Type: ModuleNotFoundError at /api/v1/account/users/1/
Exception Value: No module named 'accounts'
is the problem due to this part :
AUTH_USER_MODEL = "accounts.User"
that does not know the accounts?
I tried even :
AUTH_USER_MODEL = "api.accounts.User"
but It does not accepted this form because It only gets app_name.UserModel
does anybody know the solution to this kind of problem??