Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write in Django a custom management command which takes a URL as a parameter?

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!';)

like image 760
Alek SZ Avatar asked Jun 22 '17 13:06

Alek SZ


People also ask

Which command line utility will you use to interact with Django project?

django-admin is Django's command-line utility for administrative tasks.

What is Runserver command in Django?

The runserver command is a built-in subcommand of Django's manage.py file that will start up a development server for this specific Django project.

Which of the following command is Django admin help command?

Run django-admin.py help to display usage information and a list of the commands provided by each application. Run django-admin.py help --commands to display a list of all available commands. Run django-admin.py help <command> to display a description of the given command and a list of its available options.


1 Answers

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.

like image 71
alfonso.kim Avatar answered Sep 25 '22 23:09

alfonso.kim