django-rich

repository·main·Indexed 41 days ago

https://github.com/adamchainz/django-rich

Extensions for using the Rich library within Django version 2.2.0. Provides pretty-printing in the Django shell, Rich-powered management commands via RichCommand, and colourized test outputs and tracebacks using RichRunner.

Tokens
1.5K
Snippets
9
Records
9
Agent score
100%

What's inside django-rich

  1. Enable Rich integration in the Django shell

    main

    To enable Rich's pretty-printing and automatic imports of Rich functions in the Django shell command, add django_rich to your INSTALLED_APPS setting.

    This feature provides automatic imports for the following functions on Django 5.2+:

    • inspect()
    • print()
    • print_json()
    • pprint()

    Note: This only affects the standard Python and bpython interpreters. For IPython support, you must follow the official Rich documentation for IPython extensions.

    INSTALLED_APPS = [
        ...,
        "django_rich",
        ...,
    ]
  2. Use RichRunner for enhanced test output

    main

    Use django_rich.test.RichRunner to get colourized test outputs and improved traceback rendering.

    Features:

    • Colourized Output: Includes Rich's default syntax highlighting for numbers, strings, URLs, etc.
    • Rich Tracebacks: Displays source code and local values per frame, with clickable file links in supported terminals.
    • Flag Support: Works with --debug-sql and --pdb flags.

    To activate, set TEST_RUNNER in your Django settings.

    TEST_RUNNER = "django_rich.test.RichRunner"
  3. Adjust output width for Rich in CI environments

    main

    When running tests in CI, Rich might default to an 80-character width if it cannot detect the terminal size, which can make tracebacks look narrow. You can override this by setting the COLUMNS environment variable.

    $ COLUMNS=120 ./manage.py test
  4. Customize RichCommand console configuration

    main

    To change how the Console is initialized in a RichCommand (for example, to disable markup or highlighting), override the make_rich_console method and pass arguments to super().

    from django_rich.management import RichCommand
    
    
    class Command(RichCommand):
        def make_rich_console(self, **kwargs):
            return super().make_rich_console(**kwargs, markup=False, highlight=False)
    
        def handle(self, *args, **options): ...
  5. Create Rich-enabled management commands with RichCommand

    main

    Use django_rich.management.RichCommand as a base class for your custom management commands to gain access to a Rich Console instance via self.console.

    Key behaviors:

    • self.console uses the command's stdout (defaults to sys.stdout).
    • Colorization respects Django's --no-color and --force-color flags.
    • You can customize the Console by overriding make_rich_console(**kwargs).
    from time import sleep
    from django_rich.management import RichCommand
    
    
    class Command(RichCommand):
        def handle(self, *args, **options):
            self.console.print("[bold blue]Frobnicating widgets:[/bold blue]")
    
            with self.console.status("Starting...") as status:
                for i in range(1, 11):
                    status.update(f"Widget {i}...")
                    sleep(1)
                    self.console.log(f"Widget {i} frobnicated.")
  6. Use RichCommand for custom Django management commands

    main

    To create Django management commands that support Rich formatting and colorized output, inherit from RichCommand instead of the standard BaseCommand.

    RichCommand automatically sets up a rich.console.Console instance available as self.console. It also handles the logic for --no-color and --force-color flags, ensuring they are not used simultaneously.

    When implementing your command, you can use self.console.print() to render rich text, tables, or other formatted content to the command's output.

    from django_rich.management import RichCommand
    
    class MyCustomCommand(RichCommand):
        help = "A command with rich output"
    
        def handle(self, *args, **options):
            self.console.print("[bold green]Success![/bold green] This is rich output.")
  7. Available auto-imports in the django-rich shell

    main

    When running the enhanced shell, the following rich functions are automatically imported and available for use in your session:

    • rich.inspect: For inspecting objects.
    • rich.print: For enhanced printing.
    • rich.print_json: For pretty-printing JSON strings.
    • rich.pretty.pprint: For pretty-printing Python objects.
    # These are available immediately upon entering the shell:
    inspect(my_object)
    print_json(my_json_string)
    pprint(my_dict)
  8. Use the enhanced django-rich shell

    main

    The django-rich package provides an enhanced version of the standard Django shell management command. When using this command, rich is automatically installed to provide pretty-printed output for all standard console interactions.

    Additionally, the shell is configured to automatically import several rich utilities, allowing you to use them immediately without manual imports.

    python manage.py shell