25

Following the documentation: https://docs.djangoproject.com/en/dev/howto/custom-management-commands/

I created my own custom command (called something else but example shown below):

from django.core.management.base import BaseCommand, CommandError
from polls.models import Poll

class Command(BaseCommand):
    args = '<poll_id poll_id ...>'
    help = 'Closes the specified poll for voting'

    def handle(self, *args, **options):
        for poll_id in args:
            try:
                poll = Poll.objects.get(pk=int(poll_id))
            except Poll.DoesNotExist:
                raise CommandError('Poll "%s" does not exist' % poll_id)

            poll.opened = False
            poll.save()

            self.stdout.write('Successfully closed poll "%s"' % poll_id)

        return "Yay"

The question is how come returning a string like "Yay" does not work? Am I doing it wrong or is it not possible?

When I call the custom command from my view, I do something like:

     value = call_command('call_custom_command', parameter)
     print value

but the value is shown to be None.

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
Alf
  • 832
  • 1
  • 8
  • 17

1 Answers1

35

If you want to get the output of call_command(), you need to capture stdout. Here's how you can do it:

out = StringIO()
call_command('call_custom_command', stdout=out)

value = out.getvalue()
print value

This technique is actually used in django tests for testing management commands.

Demo:

>>> from django.core.management import call_command
>>> from StringIO import StringIO
>>> out = StringIO()
>>> call_command('validate', stdout=out)
>>> out.getvalue()
'0 errors found\n'

Hope that helps.

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • 1
    Yes it totally worked. the stdout will get both your self.stdout.write('values') and your return value; So, I parsed the entire out.getvalue() and everything works. Thanks! – Alf Mar 22 '14 at 00:38
  • 4
    # for python3 use ->> from io import StringIO – mh-samiei Feb 25 '20 at 08:35
  • This works if you `return` something from the management command. If you just print, it won't work – Cagatay Barin Oct 19 '21 at 13:54