How do I write a custom control command in Django that takes a URL as a parameter?
I am a contributor to writing custom control commands in Django. I would like to write a command that will use the given URL as a parameter. Something like:
python manage.py command http://example.com
I have read the documentation but it is not clear to me how to do this. But I can write the command "Hello World!";)
+3
source to share
1 answer
try this:
create a pod file 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 invoke 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 a description of your command and argument.
if you don't want to name the argument (part --url
) 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.
+5
source to share