custom django-admin commands - AttributeError: 'Command' object has no attribute 'stdout'

我与影子孤独终老i 提交于 2019-12-06 09:11:11

It looks like the mapping to self.stdout is a very new change in Django's trunk version, committed in May. If you're running the 1.2 release or earlier, this won't work - and you should be using the earlier documentation.

Since this is the first hit on Google I'll write another solution to another problem with the same error message: If your class Command implements __init__, it has to call __init__ of the superclass.

This will work:

from django.core.management.base import BaseCommand

class Command(BaseCommand):

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

This won't work:

from django.core.management.base import BaseCommand

class Command(BaseCommand):

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

There are two easy solutions here. The simple one is to simply convert all of your self.stdout lines to print statements instead.

That's an OK solution and you can do it.

The better solution, since self.stdout is set up in the execute() method, is to...run the execute() method.

So instead of:

Command().handle()

Do:

Command().execute()

That'll set up the self.stdout variable correctly and you'll be off and running.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!