[Answered ]-Django – where put argparse command to modify -h option?

1👍

You probably ought not to introduce argparse into the picture here. Argparse and Argh are pretty usefull if you are writing a django CLI but not very helpful for adding a custom management command because the management api has most the requirements already built in albeit in a very different way.

For example, you can automatically get your command to show up when ./manage.py -h is executed merely by placing the .py file in the right location. For example if you create a file as

myapp/management/commands/custom.py

executing manage.py -h will reveal

[myapp]
    custom

You can customize it further by over setting the help variable.

class Command(BaseCommand):
    help = 'Custom help message here'

Now ./manage.py custom -h will reveal (among other things)

Closes the specified poll for voting
👤e4c5

1👍

Adding a new answer based on discussions.

You can keep your teacher happy by moving what’s under the __main__ block to a separate function. So you have two functions in manage.py, the first one get’s called when the argument is -h, the second one for everything else. Make sure that all the imports in manage.py are also moved to inside those functions rather than being at the top level.

Then

if __name__ == "__main__":
    import sys
    if len(sys.argv) == 2 and sys.argv[1] == '-h':
        help_parser()
    else:
        main()

Where main() contains the standard django manage.py code. Notice that you don’t really need argparse here because now help_parser() only displays the help message for your app and doesn’t have anything else to do.

👤e4c5

Leave a comment