gpt4 book ai didi

Django自定义管理命令: AttributeError: 'module' object has no attribute 'Command'

转载 作者:行者123 更新时间:2023-12-03 02:02:21 25 4
gpt4 key购买 nike

我正在尝试创建自定义管理命令,如此处文档中所示:https://docs.djangoproject.com/en/dev/howto/custom-management-commands/

当我尝试从项目目录运行命令时,遇到以下错误:

AttributeError: 'module' object has no attribute 'Command'

这是文件:

#event_expiration.py
from django.core.management.base import BaseCommand, CommandError
from app.models import Event
import datetime

class Command(BaseCommand):
help = 'deletes expired events'

def handle(self, *args, **options):

today = datetime.datetime.now()
events = Event.objects.filter(date=datetime.date(2011,11,11))

for e in events:
e.delete()

self.stdout.write('Expired events successfully deleted.')

我正在运行的命令是:

$ python manage.py event_expiration

我已确保在管理和命令文件夹中添加 event_expiration.py 文件,并且这些文件夹具有 init 文件。这些位于我的应用程序文件夹之一中。

我在这里忽略了什么吗?感谢任何帮助,谢谢!

编辑:

SO 用户 Yuji 帮助我尝试对此进行调试,但我们仍然感到困惑。这就是我们所做的:

首先,完整的回溯和命令:

(venv)matt@inspirion14z:~/Dropbox/PROD/ersvp.it$ python manage.py event_expiration
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/matt/Dropbox/PROD/ersvp.it/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 443, in execute_from_command_line
utility.execute()
File "/home/matt/Dropbox/PROD/ersvp.it/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 382, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/matt/Dropbox/PROD/ersvp.it/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 261, in fetch_command
klass = load_command_class(app_name, subcommand)
File "/home/matt/Dropbox/PROD/ersvp.it/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 70, in load_command_class
return module.Command()
AttributeError: 'module' object has no attribute 'Command'

为了查看 django/core/management/init.py"中发生的情况,第 70 行我在文件中放置了 import pdb; pdb.set_trace() 。

在 Debug模式下我们尝试过:

module.__file__ 

检查模块是否符合预期,并且确实符合预期,输出为:

'/home/matt/Dropbox/PROD/ersvp.it/app/management/commands/event_expiration.pyc'

接下来,我们尝试在 shell 中手动导入 Command:

>>> from app.management.commands.event_expiration import Command 
Traceback (most recent call last): File "<console>", line 1, in <module> ImportError: cannot import name Command

还是摸不着头脑!

最佳答案

我遇到了同样的问题,问题是我的命令类没有被准确地称为 Command,正如文档所说。示例:

class Command(NoArgsCommand):
# Do something here

关于Django自定义管理命令: AttributeError: 'module' object has no attribute 'Command' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11910591/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com