Search code examples
pythondjangodjango-settingsdjango-apps

Larger Django project with mulptiple levels of subfolders with 20 apps


I am working on larger Django project which needs multiple levels of subfolders, for example applications/examples/example_1 where the app is.

When adding this app to settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'home_app.apps.HomeAppConfig',
    'applications.examples.example_1.apps.Example1Config',
]

home_app works well, but example_1 give this

error:

django.core.exceptions.ImproperlyConfigured: Cannot import 'example_1'. Check that 'applications.examples.example_1.apps.Example1Config.name' is correct.

My app.py in example_1 is this:

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

structure of project:

C:.
│   db.sqlite3
│   manage.py
│
├───applications
│   ├───examples
│       ├───example_1
│           │   admin.py
│           │   apps.py
│           │   models.py
│           │   tests.py
│           │   views.py
│           │   __init__.py
│           │
│           ├───migrations
│           │       __init__.py
│           │
│           └───__pycache__
│                   apps.cpython-311.pyc
│                   __init__.cpython-311.pyc
│
├───home_app
│   │   admin.py
│   │   apps.py
│   │   models.py
│   │   tests.py
│   │   urls.py
│   │   views.py
│   │   __init__.py
│   │
│   ├───migrations
│   │   │   __init__.py
│   │   │
│   │   └───__pycache__
│   │           __init__.cpython-311.pyc
│   │
│   ├───static
│   │       background_img.jpg
│   │
│   ├───templates
│   │   └───home_app
│   │           about.html
│   │           base.html
│   │           home.html
│   │
│   └───__pycache__
│           admin.cpython-311.pyc
│           apps.cpython-311.pyc
│           models.cpython-311.pyc
│           urls.cpython-311.pyc
│           views.cpython-311.pyc
│           __init__.cpython-311.pyc
│
└───Project
        asgi.py
        settings.py
        urls.py
        wsgi.py
        __init__.py

Solution

  • There were two issue with the code:

    1. as @Jimmy Pells commented, __init__.py needed to be added to each level of the tree: applications/__init__.py and applications/examples/__init__.py not just on app level.

    1. apps.py in the app level should be:
    from django.apps import AppConfig
    class Example1Config(AppConfig):
        default_auto_field = 'django.db.models.BigAutoField'
        name = 'applications.examples.example_1'
    

    not just:

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