user8817894
user8817894

Reputation:

Django Management Command does not import correctly

I am trying the execute a management command in Django that doesn't quite correctly import the modules.

My project structure is as follows:

myproject/
|-- appname/
|  |-- __init__.py
|  |-- management/
|  |   |-- commands/
|  |   |   |-- __init__.py
|  |   |   |-- somefile.py
|  |   |--__init__.py
|  |-- migrations/
|  |-- admin.py
|  |-- apps.py
|  |-- views.py
|  |-- models.py
|  |-- urls.py
|-- myproject/
|   |-- __init__.py
|   |-- settings.py
|   |-- urls.py
|   |-- wsgi.py
|-- manage.py

File myapp/apps.py:

from django.apps import AppConfig

class MyAppConfig(AppConfig):
    name = 'myapp'

File myapp/__init__.py

default_app_config = 'myapp.apps.MyAppConfig'

File myapp/management/commands/somefile.py

from django.core.management import BaseCommand
from django.utils.datetime_safe import datetime

from myproject.myapp.models import Car

class Command(BaseCommand):
    help = "Create initial data"
    def handle(self, *args, **options):
        cars = Car.objects.all()
        print(cars)
        self.stdout.write('Command successfully executed!')

The error:

Traceback (most recent call last):
  File "myapp/management/commands/somefile.py", line 4, in <module>
  from myproject.myapp.models import Car ModuleNotFoundError: No module named 'myproject'

How do I configure the app to have the management command address the correct dir?

Upvotes: 1

Views: 1374

Answers (1)

Ralf
Ralf

Reputation: 16495

Normally (inside the command or inside any other app of the same project) I just import from myapp, not from myproject.

Have you tried this:

from myapp.models import Car

instead of

from myproject.myapp.models import Car

Upvotes: 0

Related Questions