liveBook · Manning

Add_arguments()

As explained in Django in Action

add_arguments() is the Django management-command method that receives an argument parser and registers command-line arguments.

add_arguments() configures a Django management command's command-line interface. Django's BaseCommand supplies the argument parser; this method receives it and registers positional arguments or flags through parser.add_argument(). section 9.3 section 9.6

Use the method to define how users supply command-line input:

  • Register flags with leading dashes, such as --last_name, and optionally provide a short form such as -l. section 9.3
  • Pass help text to describe each argument in the command's automatically available help screen. section 9.3 section 9.6
  • Let handle() receive the parsed positional arguments and flags through its options parameter. section 9.6

Filtering the musicians command

A musicians command can define parser.add_argument("--last_name", "-l", help="Query musicians by last name") alongside --first_name and --birth. Users can then run python manage.py musicians --last_name Loblaw or combine --first_name O with --last_name B. Invalid input such as --birth tomorrow can produce a concise CommandError.

How Django in Action covers it

How deep it goes
Explains parser registration, flag naming, help text, and parsed options, while deferring argparse's wider configuration choices.
Examples
Uses musicians filtering flags for last name, first name, and birth date, including combined queries and invalid-date handling.
What it assumes
Starts argparse usage from the supplied parser and does not require prior familiarity with argparse.
What you can do after
Build command-line interfaces by applying Django's management-command framework and registering arguments through the supplied parser.
How it connects
Connects Django management commands with BaseCommand, argparse, add_argument(), handle(), flags, positional arguments, and CommandError.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Django in Action. The section links point to the parts of the book it draws on.