Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two arguments in django-admin custom command

I have a working django-admin custom command that I use to populate my database with new information. Again, everything works.

However, I have now changed my models and function slightly to accept two arguments as a tuple - first name and last name, instead of just "name".

Previous code below - working. Run using "manage.py xyz name1 name2 name3... etc. (space between the different args)

from django.core.management.base import BaseCommand, CommandError
from detail.models import ABC
from detail.parser import DEF

class Command(BaseCommand):
    args = '<name...>'
    help = 'Populates the ABC class database'

    def handle(self, *args, **options):
        for symbol in args:

            try:
                info = DEF(name)

Is it possible to pass on two arguments from the django-admin custom command where the second argument is optional --> i.e. (first, last=None)?

Pseudocode below of what I'd like to run using... "manage.py xyz (first1, last1) (first2, last2) <-- or some variation of this

I've already changed the function DEF to accept this appropriately as a standalone function. I'm just not sure how I can get the django-admin command working now.

like image 694
snakesNbronies Avatar asked May 13 '12 02:05

snakesNbronies


1 Answers

It's entirely possible, although django.core.management does not provide a specific tool to do so. You can parse the arguments passed via the args keyword argument. You'll have to come up with a syntax for doing so (defining the syntax in the help attribute of the command would probably be a good idea).

Assuming the syntax is firstname.lastname, or just firstname in the case that the last name is omitted, you can do something like:

def handle(self, *args, **options):
    for arg in args:
        try:
            first_name, last_name = arg.split('.')
        except ValueError:
            first_name, last_name = arg, None

        info = DEF(first_name, last_name)

And users of the command can pass in arguments like so:

$ python manage.py yourcommand -v=3 john.doe bill patrick.bateman
like image 120
modocache Avatar answered Sep 26 '22 21:09

modocache