【问题标题】:separate python script cannot find self-defined module inside Django单独的python脚本在Django内部找不到自定义模块
【发布时间】:2016-12-17 06:32:09
【问题描述】:

这是我的 Django 应用文件夹结构

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

在我的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, ...

当我在dashboard 中运行python email_excel_reports.py 时出现此错误

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'

请记住,当我运行 python email_excel_reports.py 时,我正在使用 nginx 运行 gunicorn,因此 django 应用程序运行成功。

__init__.py 里面的warehouse

default_app_config = 'warehouse.apps.WarehouseConfig'

当我运行python manage.py shell 然后键入相同的代码行时,运行代码没有问题。

我该如何克服这个错误?

重新打开 -- 为什么?

仅仅是因为修复是将python manage.py shell &lt;放在python脚本文件的前面,而这个修复在所谓的重复问题的答案中不可用。

【问题讨论】:

  • 您的warehouse 目录中有__init__.py 文件吗?
  • 是的,我刚刚将内容添加到问题中
  • 当你想在命令行中运行这个脚本时,你需要设置django环境。
  • 我在运行 python 脚本时已经在运行 gunicorn 和 nginx。我读了关于使用 django for CLI 工具的问题。所以我需要在 manage.py 中添加# Setup django import django django.setup()

标签: python django django-models


【解决方案1】:

由于需要包含 django 模块,所以运行它的更好方法是

python manage.py shell &lt; dashboard/email_excel_reports.py

【讨论】:

    猜你喜欢
    • 2018-10-15
    • 2020-01-18
    • 1970-01-01
    • 1970-01-01
    • 2014-07-19
    • 2019-05-27
    • 1970-01-01
    • 1970-01-01
    • 2021-07-14
    相关资源
    最近更新 更多