Home > Blockchain >  Can't import modules
Can't import modules

Time:06-23

I've searched for this problem and tried different solutions but can't fix it. In my Django project I have different apps and a non-app directory called 'testing_utils' with modules which serve for a testing purposes. In particular I want to import all available models to file dummy_factory.py. However when I simply import modules from my apps like so:

from abc import ABC
from datetime import date
from users.models import User

I get the error message

ModuleNotFoundError: No module named 'users'

Which is strange since I definetley can import models to some_app.views.py and access them. Here's an example of my project's directory:

/home/user/dev/project/
▸ project/
▾ testing_utils/
    dummy_factory.py
▾ users/
  ▸ __pycache__/
  ▸ migrations/
  ▸ templates/
  ▸ tests/
    __init__.py
    admin.py
    apps.py
    models.py
    views.py
  manage.py*

CodePudding user response:

/home/user/dev/project/ needs to be in your PYTHONPATH to be able to be imported.

If your testing_utils is meant to be local only, the easiest way to accomplish this is to add:

import sys
sys.path.append('/home/user/dev/project/')

... in dummy_factory.py before importing the module.

Solutions that would be more proper would be to install users (how exactly you'd make your package installable depends on your system and what version of Python and Pip you need to support), or to use a virtualenv that automatically adds the right directories to PYTHONPATH.

  • Related