15

我按照本教程创建了以下自定义管理命令。

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))
            )
        )

它完全按照我的意愿工作,但我想添加一个确认步骤,以便在for user in users:循环之前询问您是否真的要向 N 个用户发送消息 X,如果您选择“否”,该命令将中止。

我认为这很容易做到,因为它发生在一些内置的管理命令中,但它似乎没有在教程中涵盖这一点,即使在搜索和查看了内置管理命令的源代码之后,我自己无法弄清楚。

4

1 回答 1

19

你可以使用 Python 的raw_input/input函数。这是 Django源代码中的示例方法:

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"

django.utils.six.moves如果您的代码应该与 Python 2 和 3 兼容,请务必使用 import from ,或者raw_input()如果您使用的是 Python 2,请务必使用。input()在 Python 2 上,将评估输入而不是将其转换为字符串。

于 2016-08-31T19:24:30.037 回答