Skip to content

Django projects

django-typer turns Typer apps into Django management commands. Its Typer class is a typer.Typer, so command and add_typer work on it: aliases, ASCII banners, **kwargs options and classes as command groups. Add typer-di for shared options such as --database or --username.

Every example below is a complete shop/management/commands/<name>.py file, run with python manage.py <name> ....

Setup

$ pip install typer-swissknife django-typer typer-di
# settings.py
INSTALLED_APPS = [
    # ...
    "django_typer",
    "shop",
]

Versions

django-typer 4.x needs Typer 0.29, Django 5.2 or later and Python 3.11 or later. typer-swissknife needs Python 3.12 or later. The examples were run with django-typer 4.3.0 and typer-di 0.1.5.

In a function command, self is the Django command instance, so self.stdout, self.style and the other BaseCommand attributes work. A function without self works too.

Add commands to a class-based command

Define the TyperCommand as usual, then add more commands to its typer_app:

# shop/management/commands/shop.py
from django_typer.management import TyperCommand, command

import typer_swissknife as sk


class Command(TyperCommand):
    help = "Manage the shop."

    @command()
    def ping(self) -> None:
        """Check that the command runs."""
        self.stdout.write("pong")


app = Command.typer_app


@sk.command(app, aliases=("st",), ascii_name="Shop")
def status(self, verbose: bool = False) -> None:
    """Show whether the shop is open."""
    self.stdout.write(self.style.SUCCESS("The shop is open."))

    if verbose:
        self.stdout.write(f"Running as {type(self).__module__}")
$ python manage.py shop --help
 Commands
  ping          Check that the command runs.
  status (st)   Show whether the shop is open.

$ python manage.py shop st --verbose
The shop is open.
Running as shop.management.commands.shop

$ python manage.py shop st --help     # starts with the "Shop" banner

Typer-style commands with undeclared options

With the module-level Typer app, use sk.command(app) where you would write @app.command(). A **kwargs parameter collects options you did not declare:

# shop/management/commands/seed.py
from django_typer.management import Typer

import typer_swissknife as sk

app = Typer(help="Seed demo data.")


@sk.command(app, aliases=("r",))
def rows(self, **counts: int) -> None:
    """Create rows per model, for example --users 10 --orders 5."""
    for model, count in counts.items():
        self.stdout.write(f"{model}: {count}")


@sk.command(app)
def wipe(self, yes: bool = False) -> None:
    """Delete all demo data."""
    self.stdout.write("wiped" if yes else "pass --yes to wipe")
$ python manage.py seed r --users 10 --orders 5
users: 10
orders: 5

$ python manage.py seed wipe --yes
wiped

Shared options with typer-di

typer-di's TyperDI adds Depends to app.command(). django-typer always creates its own Typer class, so give that app the TyperDI behaviour once, in a small helper. Keep the dependencies next to it:

# shop/cli.py
from typing import Annotated

import typer
from django.contrib.auth import get_user_model
from django.db import connections
from typer_di import Depends, TyperDI


def with_di(app):
    """Make `app` resolve typer-di `Depends` in commands registered after this call."""
    app.__class__ = type("DITyper", (TyperDI, type(app)), {})

    return app


def get_database(database: str = typer.Option("default", "--database", help="Database alias.")) -> str:
    if database not in connections:
        raise typer.BadParameter(f"unknown database {database!r}", param_hint="--database")

    return database


def get_user(
    database: Annotated[str, Depends(get_database)],
    username: str = typer.Option(..., "--username", "-u"),
):
    User = get_user_model()

    try:
        return User.objects.using(database).get(username=username)
    except User.DoesNotExist:
        raise typer.BadParameter(f"no user {username!r}", param_hint="--username") from None

Each command that asks for get_user gets --username and --database, and the user is loaded before the command runs. Dependencies can be combined with **kwargs:

# shop/management/commands/users.py
from typing import Annotated

from django.contrib.auth import get_user_model
from django.contrib.auth.models import AbstractUser
from django_typer.management import Typer
from typer_di import Depends

import typer_swissknife as sk
from shop.cli import get_database, get_user, with_di

app = with_di(Typer(help="Manage users."))


@sk.command(app, aliases=("s",))
def show(self, user: Annotated[AbstractUser, Depends(get_user)]) -> None:
    """Show one user."""
    self.stdout.write(f"{user.username} <{user.email}>")


@sk.command(app, aliases=("u",))
def update(self, user: Annotated[AbstractUser, Depends(get_user)], **fields: str) -> None:
    """Set any user field, for example --email bob@example.com --first-name Bob."""
    for field, value in fields.items():
        setattr(user, field, value)

    user.save(update_fields=list(fields))
    self.stdout.write(f"updated {', '.join(fields)} on {user.username}")


@sk.command(app)
def count(self, database: Annotated[str, Depends(get_database)]) -> None:
    """Count users in a database."""
    self.stdout.write(str(get_user_model().objects.using(database).count()))
$ python manage.py users s -u bob
bob <bob@old.example>

$ python manage.py users u -u bob --email bob@example.com --first-name Bob
updated email, first_name on bob

$ python manage.py users s -u nobody     # prints the help page, then:
...
no user 'nobody'

$ python manage.py users count --database other
...
unknown database 'other'

Use with_di, not create_di_wrapper, with **kwargs

typer_di.create_di_wrapper(fn) also resolves Depends, but it turns **kwargs into a required argument named after it. with_di resolves dependencies after command has handled **kwargs, so both work together.

Classes as command groups

Pass a class to add_typer to turn its @sk.command() methods into a group. The __init__ parameters become options of every command in the group. In a method, self is the class instance. Use get_current_command() to reach the Django command:

# shop/management/commands/inventory.py
import typer
from django_typer.management import Typer
from django_typer.utils import get_current_command

import typer_swissknife as sk

app = Typer(help="Manage inventory.")


class Stock:
    """Manage stock levels."""

    def __init__(self, warehouse: str = typer.Option("main", "--warehouse", "-w")) -> None:
        self.warehouse = warehouse
        self.out = get_current_command().stdout

    @sk.command(name="list", aliases=("ls",))
    def list_items(self, low: bool = False) -> None:
        """List items in the warehouse."""
        self.out.write(f"items in {self.warehouse}{' (low only)' if low else ''}")

    @sk.command()
    def adjust(self, sku: str, by: int) -> None:
        """Change the stock of SKU by a number of units."""
        self.out.write(f"{sku} {by:+d} in {self.warehouse}")

    def helper(self) -> None:
        """Not a command: it has no @sk.command()."""


class Prices:
    """Manage prices."""

    def __init__(self, currency: str) -> None:
        self.currency = currency

    @sk.command()
    def show(self, sku: str) -> None:
        """Show the price of SKU."""
        typer.echo(f"{sku}: 9.99 {self.currency}")


stock = sk.add_typer(app, Stock, aliases=("s",))
sk.add_typer(stock, Prices(currency="USD"))
$ python manage.py inventory s ls -w east --low
items in east (low only)

$ python manage.py inventory stock adjust ABC 5 --warehouse north
ABC +5 in north

$ python manage.py inventory stock prices show ABC
ABC: 9.99 USD
  • Stock is a class, so it is created for every call and --warehouse is an option of each of its commands.
  • Prices(currency="USD") is an instance: it is used as is, and its __init__ parameters are not options.
  • add_typer returns the sub-app, so prices nests inside stock.

Dependencies in a class group

On a with_di app, Depends also works in __init__. Every command of the group then gets the loaded user through self:

# shop/management/commands/orders.py
from typing import Annotated

from django.contrib.auth.models import AbstractUser
from django_typer.management import Typer
from django_typer.utils import get_current_command
from typer_di import Depends

import typer_swissknife as sk
from shop.cli import get_user, with_di

app = with_di(Typer(help="Manage orders."))


class Orders:
    """Orders of one user."""

    def __init__(self, user: Annotated[AbstractUser, Depends(get_user)]) -> None:
        self.user = user
        self.out = get_current_command().stdout

    @sk.command(name="list", aliases=("ls",))
    def list_orders(self, **filters: str) -> None:
        """List orders, filtered by any field: --status paid --city Paris."""
        self.out.write(f"orders of {self.user.username} where {filters}")

    @sk.command()
    def cancel(self, order_id: int) -> None:
        """Cancel one order."""
        self.out.write(f"cancelled #{order_id} for {self.user.username}")


sk.add_typer(app, Orders, name="of", aliases=("o",))


@sk.command(app)
def total(self) -> None:
    """Total of all orders."""
    self.stdout.write("0.00")
$ python manage.py orders o ls -u bob --status paid --city Paris
orders of bob where {'status': 'paid', 'city': 'Paris'}

$ python manage.py orders of cancel 7 --username bob
cancelled #7 for bob

Calling commands from code and tests

call_command works with all of the above. Pass options that come from a dependency or from **kwargs as command-line strings. Declared options can also be keywords:

from io import StringIO

from django.core.management import call_command

out = StringIO()

call_command("users", "show", "-u", "bob", stdout=out)
call_command("orders", "o", "ls", "-u", "bob", "--status", "paid", stdout=out)
call_command("seed", "rows", "--users", "3", stdout=out)
call_command("inventory", "stock", "adjust", "ABC", "2", warehouse="east", stdout=out)
call_command("shop", "status", verbose=True, stdout=out)

Limitations

  • with_di only changes commands registered after it. Commands defined with django-typer's own @command() inside a TyperCommand class body are registered when the class is created, so they do not resolve Depends. Use typer_di.create_di_wrapper on those (without **kwargs), or register them with sk.command(Command.typer_app) after a with_di(Command.typer_app) call.
  • call_command("users", "show", username="bob") fails with "Missing parameter": options added by a dependency must be passed as strings ("-u", "bob").