将确认步骤添加到自定义Django management/manage.py命令

ele*_*han 7 python django django-manage.py django-management-command

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

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))
            )
        )
Run Code Online (Sandbox Code Playgroud)

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

我认为这可以很容易地完成,因为它发生在一些内置的管理命令中,但它似乎没有涵盖在教程中,甚至在一些搜索和查看内置管理命令的源之后,我无法独自解决这个问题.

knb*_*nbk 10

你可以使用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"
Run Code Online (Sandbox Code Playgroud)

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