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!';)
django-admin is Django's command-line utility for administrative tasks.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With