1
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
    def handle(self, *args, **options):
        ......
        self.handle_noargs()

    def handle_noargs(self, **options):
        packages_count = Package.objects.all().count()
        Package.objects.all().delete()
        print >> self.stdout, u'Deleted %d packages' % packages_count
        ......

I am writing tests for provided code, but whenever I call handle_noargs function I receive following error :

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

I am using Django 1.3.1.

>>> import django
>>> django.VERSION
(1, 3, 1, 'final', 0)

Regarding googling answer stdout was implemented in BaseCommand class some versions ago so I have no idea why django cant find it.

Adding dir(self):

>>> from webui.packagedb.management.commands.packagedb_clear import Command
>>> dir(Command)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribut
e__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_e
x__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_
_weakref__', 'args', 'can_import_settings', 'create_parser', 'execute', 'get_ver
sion', 'handle', 'handle_noargs', 'help', 'option_list', 'output_transaction', '
print_help', 'requires_model_validation', 'run_from_argv', 'usage', 'validate']
  • Don't know anything about Django, but is that meant to be `self.stdout` or `sys.stdout`? – NPE Dec 18 '12 at 12:22
  • 2
    show pls `print dir(self)` result – Alexey Kachayev Dec 18 '12 at 12:24
  • possible duplicate of [custom django-admin commands - AttributeError: 'Command' object has no attribute 'stdout'](http://stackoverflow.com/questions/3167795/custom-django-admin-commands-attributeerror-command-object-has-no-attribute) – mlissner Oct 22 '14 at 20:25

1 Answers1

2

i think you can not call handle_noargs directly, the BaseCommand class command has an execute() method which calls handle() and before initializes stdout and stderr

so every time you run a command, the execute() method is called which expects the handle method to be implemented

Christian Thieme
  • 1,114
  • 6
  • 6
  • I dont call it directly, I call it trough handle() when handle has no arguments. Same in tests. –  Dec 18 '12 at 12:41
  • you shouldnt call handle either, since all the initialization stuff is done in execute(), and without that your command may not produce the expected results – Christian Thieme Dec 18 '12 at 12:45