[Fixed]-Python relative import error?

1👍

Add __init__.py in main folder instead of src folder. Then try to import using from main.models import exampleClass. It should be working.

0👍

How did you set $PYTHONPATH variable ? The search paths are relative to this environment variable.

So if you want to specify a path like main.models, it should contain the src directory.

Note that you can also manage it with the sys.path array.

Django normally add all the applications to sys.path. You may try to print it inside the settings.py file to have an idea.

To add a path from the settings.py file of the project, you could do something like:

import os.path
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
sys.path.append(os.path.join(BASE_DIR, "../lib"))

If for example you have a lib directory at the same level as the directory that contains the settings.py file.

0👍

You don’t need .. if main and lib are both django’s apps, and you have registered them in INSTALLED_APPS settings.

If main and lib are in the same level that manage.py:

src/
    main/
        ...
    lib/
        ...
    manage.py
    ...

You just need:

from main.models import exampleClass
👤Gocht

Leave a comment