我按照本教程创建了以下自定义管理命令。
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,如果您选择“否”,该命令将中止。
我认为这很容易做到,因为它发生在一些内置的管理命令中,但它似乎没有在教程中涵盖这一点,即使在搜索和查看了内置管理命令的源代码之后,我自己无法弄清楚。