separate python script cannot find self-defined module inside Django

Question:

This is my Django app folder structure

|-----tt
|      |--settings.py
|
|-----warehouse
|       |--models.py
|       |--__init__.py
|
|-----dashboard
|       |--email_excel_reports.py
|

Inside my email_excel_reports.py

# for ORM query
from warehouse.models import EntryFormLineItem
from django.db.models import Sum
from django.db.models.functions import Coalesce
from django.utils import timezone


line_items = EntryFormLineItem.objects.filter(approved_by__isnull=False, ...

I got this error when I run python email_excel_reports.py inside dashboard

Traceback (most recent call last):
  File "/vagrant/dashboard/email_excel_reports.py", line 11, in <module>
    from warehouse.models import EntryFormLineItem
ImportError: No module named 'warehouse'

Bear in mind that when I run the python email_excel_reports.py I was running gunicorn with nginx, so the django app is running successfully.

The __init__.py inside warehouse

default_app_config = 'warehouse.apps.WarehouseConfig'

When I run python manage.py shell and then type the same lines of code, there was no problem running the code.

How do I get over the error?

RE-OPEN — WHY?

Simply because the fix was to have python manage.py shell < placed in front of the python script file and this fix was not available in the supposedly duplicated question’s answers.

Asked By: Kim Stacks

||

Answers:

Because of the need to include the django modules, the better way to run this is

python manage.py shell < dashboard/email_excel_reports.py

Answered By: Kim Stacks

I just solved this problem by putting the standalone Python file into the same directory as manage.py. (Since it’s in the project root directory, all the modules are available beneath it).

Answered By: Derek Smith
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.