8

I am learning to write custom management commands in Django. I would like to write a command which would take a given URL as a parameter. Something like:

python manage.py command http://example.com

I've read a documentation, but it is not clear to me how to do this. But I can write a command saying 'Hello World!';)

1 Answer 1

22

try this:

create a file under yourapp/management/commands/yourcommand.py with the following content:

from django.core.management.base import BaseCommand

class Command(BaseCommand):
    help = 'A description of your command'

    def add_arguments(self, parser):
        parser.add_argument(
            '--url', dest='url', required=True,
            help='the url to process',
        )

    def handle(self, *args, **options):
        url = options['url']
        # process the url

then you can call your command with

python manage.py yourcommand --url http://example.com

and either:

python manage.py --help

or

python manage.py yourcommand --help

will show the description of your command and the argument.

if you don't want to name the argument (the --url part), like in your example, just read the url('s) form args:

def handle(self, *args, **kwargs):
    for url in args:
        # process the url

hope this helps.

4
  • Good example. But the question only deals with one URL. So drop the '--' in front of add_argument and it'll work magically (well, thanks to argparse).
    – user1600649
    Jun 22, 2017 at 14:03
  • Thanks! This helps a lot! But I don't understand the last part (without --url) - what should be after: for url in args:
    – Alek SZ
    Jun 22, 2017 at 14:11
  • @AlekSZ, that is up to you, there you process the URL given as argument. Jun 22, 2017 at 14:13
  • 1
    perfectly explained
    – cwhisperer
    Jun 4, 2018 at 8:21

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.