-1

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.

Kim Stacks
  • 10,202
  • 35
  • 151
  • 282
  • is there a `__init__.py` file in your `warehouse` directory? – shady Dec 17 '16 at 06:43
  • yes and I have just added the contents into the question – Kim Stacks Dec 17 '16 at 06:46
  • You need to set up django environment, when you want to run this script in command line. – shady Dec 17 '16 at 06:52
  • I am already running gunicorn and nginx when I run the python script. And I read the question about using django for CLI tool. So I need to add `# Setup django import django django.setup()` inside manage.py? – Kim Stacks Dec 17 '16 at 07:06

2 Answers2

0

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

Kim Stacks
  • 10,202
  • 35
  • 151
  • 282
0

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).

Julia Meshcheryakova
  • 3,162
  • 3
  • 22
  • 42