Django file structure: cannot import main module without export PYPATH
Asked Answered
G

1

0

I am using Django 4.0.4

Here is my project structure:

root/
|   README.md
|-- app/
|   |-- init__.py
|   |-- manage.py
|   |-- project/
|   |   |-- __init__.py
|   |   |-- settings.py
|   |   |-- urls.py
|   |   |-- etc...
|   |-- webapp/
|   |   |-- __init__.py
|   |   |-- apps.py
|   |   |-- views.py
|   |   |-- utils/
|   |   |-- migrations/
|   |   |-- etc...
|   |-- mediafiles/
|-- docs/

The imports inside de files are structured like this:

  • apps.py => from app.project.settings import APP_NAME
  • settings.py => from app.webapp.utils.paths import BASE_DIR
  • urls.py => from app.webapp.views import home
  • views.py => from app.webapp.models import MyModel

In settings.py

INSTALLED_APPS = [
    "webapp",
    ...
]

In short, nothing very unusual, except that my root folder is one level higher than in a standard Django installation. However, as soon as I run

python app/manage.py runserver localhost:8000
# OR
python manage.py runserver localhost:8000 # (inside the `app/` directory)

I get a ModuleNotFoundError: No module named 'app'

The problem is fixed if I set the PYTHONPATH variable inside the root/ directory:

export PYTHONPATH="$(pwd)"

If I remove the app from my imports, then the command works but my IDE (PyCharm) no longer lets me take advantage of import autocompletion...

Why does this error happen?

Is there a way to keep the import as so without needing to export the PYTHONPATH?

Thank you so much for your help!!

Edit: Apparently this question cover the same issue but without a response that fix my problem

Gerianne answered 20/9, 2023 at 9:5 Comment(0)
G
0

I have added a line to manage.py file and its works!

#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys


def main():
    """Run administrative tasks."""
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # this line
    execute_from_command_line(sys.argv)


if __name__ == "__main__":
    main()

Gerianne answered 20/9, 2023 at 13:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.