Add confirmation step to custom Django management/manage.py command

时间:2016-08-31 18:27:44

标签: python django django-manage.py django-management-command

I created the following custom management command following this tutorial.

from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User

from topspots.models import Notification


class Command(BaseCommand):
    help = 'Sends message to all users'

    def add_arguments(self, parser):
        parser.add_argument('message', nargs='?')

    def handle(self, *args, **options):
        message = options['message']
        users = User.objects.all()
        for user in users:
            Notification.objects.create(message=message, recipient=user)

        self.stdout.write(
            self.style.SUCCESS(
                'Message:\n\n%s\n\nsent to %d users' % (message, len(users))
            )
        )

It works exactly as I want it to, but I would like to add a confirmation step so that before the for user in users: loop you are asked if you really want to send message X to N users, and the command is aborted if you choose "no".

I assume this can be easily done because it happens with some of the built-in management commands, but it doesn't seem to cover this in the tutorial and even after some searching and looking at the source for the built-in management commands, I have not been able to figure it out on my own.

1 个答案:

答案 0 :(得分:8)

您可以使用Python的'&lt &apos &gt &quot &amp' / raw_input函数。这是Django source code的一个示例方法:

input

如果您的代码应与Python 2和3兼容,请务必使用from django.utils.six.moves import input def boolean_input(question, default=None): result = input("%s " % question) if not result and default is not None: return default while len(result) < 1 or result[0].lower() not in "yn": result = input("Please answer yes or no: ") return result[0].lower() == "y" 的导入,如果您使用的是Python {2},请使用django.utils.six.moves将评估输入而不是将其转换为字符串。