Add the confirmation step to the Django / manage.py user management command

I created the following management team 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 the way I want, but I would like to add a confirmation step so that before the loop for user in users:you are asked if you really want to send messages from X to N, and the command is interrupted if you select "no."

I assume that this can be easily done because it happens with some built-in control commands, but it does not seem to cover this in the tutorial, and even after some searching and searching for a source for the built-in control commands, I could not figure it out myself.

+4
1

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, raw_input(), Python 2. input() Python 2 , .

+5

Source: https://habr.com/ru/post/1653211/


All Articles