9

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.

1 Answer 1

13

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
Sign up to request clarification or add additional context in comments.

3 Comments

THANKS! That worked well. I was originally hoping to have two separate args, but this works the same.
@modocache -v=3 ? what it will do ?
This answer is obsolete, django now has an add_arguments method built-in, which was added in v1.8. See: docs.djangoproject.com/en/2.0/howto/custom-management-commands

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.