'django.setup() in single file in 'apps' folder, got 'apps' is not a package

Solved by sys.path.insert(0, project_root) , I don't know the reason, if use sys.path.append will get this error.


Tried to create projects in apps folder, got error -- 'apps' is not a package.

init project

django-admin startproject proj
cd proj
mkdir apps
cd apps
python ..\manage.py startapp foo

apps.py

from django.apps import AppConfig
class FooConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'apps.foo'

models.py

from django.db import models
class FileModel(models.Model):
    file = models.FileField(upload_to='static/uploads')

settings.py

...
INSTALLED_APPS = [
    ...,
    'apps.foo',
]

python ..\manage.py makemigrations

python ..\manage.py migrate

tests.py

import os,sys

pwd = os.path.dirname(os.path.relpath(__file__))
sys.path.append(pwd + "../../")
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings')

import django
django.setup()

# SomeModel.objects.create(xxxx)

$ proj\apps\foo>python tests.py

Traceback (most recent call last):
  File "D:\temp\delweb2\proj\apps\foo\tests.py", line 8, in <module>
    django.setup()
  File "C:\Users\wgfabc\.pyenv\pyenv-win\versions\3.10.1\lib\site-packages\django\__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\Users\wgfabc\.pyenv\pyenv-win\versions\3.10.1\lib\site-packages\django\apps\registry.py", line 91, in populate
    app_config = AppConfig.create(entry)
  File "C:\Users\wgfabc\.pyenv\pyenv-win\versions\3.10.1\lib\site-packages\django\apps\config.py", line 223, in create
    import_module(entry)
  File "C:\Users\wgfabc\.pyenv\pyenv-win\versions\3.10.1\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1001, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'apps.foo'; 'apps' is not a package


Solution 1:[1]

you need to append an absolute path to sys.path and also a "/" would be missing in:

pwd = os.path.dirname(os.path.relpath(__file__))
sys.path.append(pwd + "../../")

above code adds something like "your_dir_name../../"

you could change it to

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1