Home > Mobile >  Import app model with multiple Django apps error ModuleNotFoundError: No module named 'apps
Import app model with multiple Django apps error ModuleNotFoundError: No module named 'apps

Time:06-28

So I have a problem importing a model from a different app in same Django project.

My files are structured as follows:

/project
    /apps  
       __init__.py
       /app1
          __init__.py
          models.py
          ...
       /non_app_dir
          __init__.py
          work.py
       ...
   /core
       __init.py
       settings.py
       urls.py
       wsgi.py
       ...  
manage.py

In my settings.py, I have this:

INSTALLED_APPS = [
    ...
    'apps.app1',
    'apps.non_app_dir',
    ...
]

Ok, so in my work.py (from non_app_dir), I try to import a model from models.py (from app1) like below:

from apps.app1.models import MyModel

def testModel():
    
    test = MyModel.objects.all()
    print(test)

but i get the following error

ModuleNotFoundError: No module named 'apps'

Any solutions to this?

CodePudding user response:

Create two seperate apps using following structure.

/project

   /app1
          __init__.py
          models.py
    
   /non_app_dir
          __init__.py
          work.py
  
   /core
       __init.py
       settings.py
       urls.py
       wsgi.py
       
    manage.py

Inside, core urls.py include urls,

    path('path1/', include('app1.urls'),
    path('path2/', include('non_app_dir.urls')

CodePudding user response:

In your app1/apps.py be sure to add name = 'apps.app1' to the app config class. Like:

from django.apps import AppConfig

class App1Config(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'apps.app1'
 
  • Related