gpt4 book ai didi

django - 自定义 django-admin 命令 - AttributeError : 'Command' object has no attribute 'stdout'

转载 作者:行者123 更新时间:2023-12-04 14:42:35 25 4
gpt4 key购买 nike

按照编写自定义 django-admin 命令的示例 here ,我创建了以下自定义命令:

from django.core.management.base import BaseCommand, CommandError

class Command(BaseCommand):
args = ''
help = 'Test command'

def handle(self, *args, **options):
self.stdout.write("Hello World!")

令人惊讶的是,我收到了以下堆栈跟踪:

Traceback (most recent call last):
File "D:\My Documents\Dev\MyProject\svn\trunk\dj_project\manage.py", line 11, in <module>
execute_manager(settings)
File "C:\Python26\lib\site-packages\django\core\management\__init__.py", line 438, in execute_manager
utility.execute()
File "C:\Python26\lib\site-packages\django\core\management\__init__.py", line 379, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Python26\lib\site-packages\django\core\management\base.py", line 191, in run_from_argv
self.execute(*args, **options.__dict__)
File "C:\Python26\lib\site-packages\django\core\management\base.py", line 218, in execute
output = self.handle(*args, **options)
File "D:\My Documents\Dev\MyProject\svn\trunk\dj_project\..\dj_project\dj_app\management\commands\mytest.py", line 8, in handle
self.stdout.write("Hello World!")
AttributeError: 'Command' object has no attribute 'stdout'

怎么会?这是一个非常基本的自定义命令,据我所知符合示例。

我正在使用 Django 1.2.1

最佳答案

由于这是 Google 上的第一次点击,我将针对具有相同错误消息的另一个问题编写另一个解决方案:如果您的类 Command 实现了 __init__,它必须调用父类(super class)的 __init__。

这会起作用:

from django.core.management.base import BaseCommand

class Command(BaseCommand):

def __init__(self, *args, **kwargs):
super(Command, self).__init__(*args, **kwargs)
... do stuff

这行不通:

from django.core.management.base import BaseCommand

class Command(BaseCommand):

def __init__(self, *args, **kwargs):
... do stuff

关于django - 自定义 django-admin 命令 - AttributeError : 'Command' object has no attribute 'stdout' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3167795/

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