Home > Mobile >  File import issue - python Django
File import issue - python Django

Time:08-28

I have a file in my management/commands folder and I am trying to import my models into the report.py folder. However, I get the following error.

Traceback (most recent call last):
  File "c:\Users\Timmeh\source\Python\Django Projects\env\topxgym\members\management\commands\report.py", line 2, in <module>
    from members.models import ActiveMember
ModuleNotFoundError: No module named 'members'

I have a active.py file in that same folder with the same import and it works. However, the active.py is run from python manage.py active. The report.py I am just compiling/running it (not running it from python manage.py). That is the only difference.

the file structure. enter image description here

CodePudding user response:

Please don't forget to add __init__.py for every folder.

More here: https://docs.python.org/3/reference/import.html#regular-packages

Try to made relative import.

from ..models import ActiveMember

if it works, this answer can help: Absolute imports in python not working, relative imports work

Try to check your project settings.

Have you add yors members app in settings.INSTALLED_APPS list?

CodePudding user response:

Here is a dirty hack which should solve the issue.

and I'll also point out an alternate one if that suits your use case.

First Option

import sys
sys.path.append(r'c:\Users\Timmeh\source\Python\Django Projects\env\topxgym')

# now your import should work
from members.models import ActiveMember

This is dirty because it manipulates sys path which is not a good practice. I'm assuming this script is just a standalone script you wish to run, hence it should not be an issue overall.

Second Option

IFF this is a possibility, you could just move your report.py and keep it inside topxgym folder (at the same level as requirements.txt)

In that case too, the same import statement would work.

side note

If you're looking to access the ORM from a standalone script, it looks like you might be missing to add the django configuration in the script as recommended by the documentation.

After your import issues are fixed by either of the above two methods, if it works, great. If it doesn't it would mean that you have to add the django.setup() config and specify a settings file.

  • Related