0

I have created a small script for comparing how similar two images are. This is contained in a file called compare_image.py, which contains just one function, compare. This file is in the app directory. I am trying to import it from the models.py file using the line import compare_image, but attempting this results in the error message ModuleNotFoundError: No module named 'compare_image'.

The simplified directory structure looks like this:

myproject
└── myapp
    ├── __init__.py
    ├── admin.py
    ├── apps.py
    ├── compare_image.py
    ├── forms.py
    ├── models.py
    ├── tests.py
    ├── urls.py
    └── views.py

myapp is the only app in the project. Apart from this, the webapp functions fine.

I have tried deleting and retouching the __init__.py file to no avail. I can import compare_image fine from a python shell in the myapp directory. The only imports in compare_image.py are to PIL or standard libraries, so I don't think circular imports are the culprit.

One solution would be to just put the code in models.py, but I don't want to clutter this file.

I thought since this error seems so basic there might be some standard mechanism for user-written scripts in Django, but I can't find any mention of this online.

I would be happy to provide more details about the project if it will make things clearer. Thanks in advance for any help (this error is driving me crazy!)

3
  • Can you post the contents of compare_image.py? Commented Jan 31, 2019 at 17:25
  • Would this answer your question? stackoverflow.com/questions/12169133/… Commented Jan 31, 2019 at 17:27
  • Thanks @cslotty, yes this is effectively the exact same problem. I thought I had tried that solution, but maybe I fixed something else in the meantime Commented Jan 31, 2019 at 19:57

1 Answer 1

0

I think you're doing an absolute import where you need a relative one. Can you try:

from .compare_image import compare

from a python file in the same folder as compare_image.py?

Sign up to request clarification or add additional context in comments.

2 Comments

Wow, I thought I had tried every combination and style of import but this really solved it! Can you shed any light on why this is necessary, when I can import the package as normal from a simple script in the same directory?
When you import a module, that module will be searched in the search path (see import sys; sys.path). If you are running a simple script, search path will have file's directory so you can import any module in the same directory. When you are using Django, Python search path will not include your directory (you can set PYTHONPATH but this is not recommended) so you would need to use relative imports.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.