Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Request input from django custom command?

Tags:

python

django

I've made a custom command in django to delete a set account in CMD, but I want to be able to run the python file and have the command line ask me for the account number to delete then have it delete. This is what I have so far.

from django.core.management.base import BaseCommand, CommandError
from accounts.models import client

class Command(BaseCommand):

    args = '<client_id client_id ...>'
    help = 'Closes the specified account.'

    def handle(self, *args, **options):
        for client_id in args:
            try:
                x = client.objects.get(pk=int(client_id))
            except client.DoesNotExist:
                raise CommandError('Client "%s" does no exist' % client_id)

            x.delete()

            self.stdout.write('Successfully closed account "%s"' % client_id)
like image 437
Jabrill Peppahs Avatar asked Feb 03 '15 14:02

Jabrill Peppahs


People also ask

How do you pass arguments in Django management command?

The parameter parser is an instance of argparse. ArgumentParser (see the docs). Now you can add as many arguments as you want by calling parser 's add_argument method. In the code above, you are expecting a parameter n of type int which is gotten in the handle method from options .

What is BaseCommand in Django?

BaseCommand is a Django object for creating new Django admin commands that can be invoked with the manage.py script. The Django project team as usual provides fantastic documentation for creating your own commands.


1 Answers

Use the built-in raw_input() function:

def handle(self, *args, **options):
    if args:
        ids = args
    else:
        ids = raw_input('Enter comma-delimited list of ids: ').split(',')
    for client_id in ids:
        ...

Edit: In Python3, use input() instead of raw_input()

like image 143
catavaran Avatar answered Oct 06 '22 03:10

catavaran