from django.core.management.base import BaseCommand, CommandError from polls.models import Question as Poll class Command(BaseCommand): help = 'Closes the specified poll for voting' def add_arguments(self, parser): parser.add_argument('poll_ids', nargs='+', type=int) def handle(self, *args, **options): for poll_id in options['poll_ids']: try: poll = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise CommandError('Poll "%s" does not exist' % poll_id) poll.opened = False poll.save() self.stdout.write(self.style.SUCCESS('Successfully closed poll "%s"' % poll_id))
Here is what the above code is Doing:
1. It defines a command, closes the poll, which takes a list of poll IDs as required arguments.
2. It configures the closes the poll command to use the poll_ids argument.
3. It defines a handle() method, which takes the poll IDs and closes the corresponding Poll objects.
4. It outputs a success message to the console for each poll it closes.