0
# Django Integration
1
2
Django-specific utilities that enable rich formatting for Django management commands with project-wide configuration support. These utilities provide seamless integration with Django's command system while maintaining compatibility with existing Django commands.
3
4
## Capabilities
5
6
### DjangoRichHelpFormatter
7
8
A rich help formatter specifically designed for Django management commands, combining Django's DjangoHelpFormatter with rich formatting capabilities.
9
10
```python { .api }
11
# From rich_argparse.django
12
class DjangoRichHelpFormatter:
13
"""A rich help formatter for django commands."""
14
```
15
16
#### Usage Examples
17
18
Using with individual Django commands:
19
20
```python
21
from django.core.management.base import BaseCommand
22
from rich_argparse.django import DjangoRichHelpFormatter
23
24
class Command(BaseCommand):
25
help = "A sample Django command with rich formatting"
26
27
def create_parser(self, prog_name, subcommand, **kwargs):
28
parser = super().create_parser(prog_name, subcommand, **kwargs)
29
parser.formatter_class = DjangoRichHelpFormatter
30
return parser
31
32
def add_arguments(self, parser):
33
parser.add_argument("--input", help="Input file path")
34
parser.add_argument("--verbose", action="store_true", help="Enable verbose output")
35
36
def handle(self, *args, **options):
37
# Command implementation
38
pass
39
```
40
41
Custom Django command with rich help:
42
43
```python
44
from django.core.management.base import BaseCommand
45
from rich_argparse.django import DjangoRichHelpFormatter
46
47
class Command(BaseCommand):
48
help = """
49
Process user data with rich formatting support.
50
51
This command demonstrates rich markup in Django command help:
52
- Use `--format json` for JSON output
53
- Use `--batch` for processing multiple files
54
- Check the [link https://docs.djangoproject.com]Django docs[/] for more info
55
"""
56
57
def create_parser(self, prog_name, subcommand, **kwargs):
58
parser = super().create_parser(prog_name, subcommand, **kwargs)
59
parser.formatter_class = DjangoRichHelpFormatter
60
return parser
61
62
def add_arguments(self, parser):
63
parser.add_argument(
64
"--format",
65
choices=["json", "csv", "xml"],
66
default="json",
67
help="Output format for processed data"
68
)
69
70
parser.add_argument(
71
"--batch",
72
action="store_true",
73
help="Process multiple files in batch mode"
74
)
75
76
parser.add_argument(
77
"--dry-run",
78
action="store_true",
79
help="""
80
Perform a dry run without making changes.
81
82
Useful for testing command arguments and seeing what
83
would be processed without actually executing the operation.
84
"""
85
)
86
```
87
88
### richify_command_line_help
89
90
Project-wide function that sets a rich default formatter class for all Django commands, affecting built-in, third-party, and user-defined commands.
91
92
```python { .api }
93
def richify_command_line_help(
94
formatter_class: type[RichHelpFormatter] = DjangoRichHelpFormatter,
95
) -> None:
96
"""
97
Set a rich default formatter class for BaseCommand project-wide.
98
99
Calling this function affects all built-in, third-party, and user defined
100
django commands. Note that this function only changes the default formatter
101
class of commands. User commands can still override the default by explicitly
102
setting a formatter class.
103
104
Args:
105
formatter_class: The rich formatter class to use as default.
106
Defaults to DjangoRichHelpFormatter.
107
"""
108
```
109
110
#### Usage Examples
111
112
Enable rich formatting for all Django commands:
113
114
```python
115
# In your Django project's __init__.py or apps.py
116
from rich_argparse.django import richify_command_line_help
117
118
# Apply rich formatting to all Django commands
119
richify_command_line_help()
120
```
121
122
Use custom formatter for all commands:
123
124
```python
125
from rich_argparse.django import richify_command_line_help, DjangoRichHelpFormatter
126
127
# Create custom formatter class
128
class CustomDjangoFormatter(DjangoRichHelpFormatter):
129
styles = {
130
**DjangoRichHelpFormatter.styles,
131
"argparse.args": "bold cyan",
132
"argparse.help": "dim white"
133
}
134
135
# Apply custom formatter to all Django commands
136
richify_command_line_help(formatter_class=CustomDjangoFormatter)
137
```
138
139
Enable in Django app configuration:
140
141
```python
142
# In your app's apps.py
143
from django.apps import AppConfig
144
145
class MyAppConfig(AppConfig):
146
default_auto_field = 'django.db.models.BigAutoField'
147
name = 'myapp'
148
149
def ready(self):
150
from rich_argparse.django import richify_command_line_help
151
richify_command_line_help()
152
```
153
154
## Complete Integration Example
155
156
### Project-wide Setup
157
158
```python
159
# myproject/__init__.py
160
from rich_argparse.django import richify_command_line_help
161
162
# Enable rich formatting for all Django commands
163
richify_command_line_help()
164
```
165
166
### Custom Command with Rich Features
167
168
```python
169
# management/commands/process_data.py
170
from django.core.management.base import BaseCommand, CommandError
171
from rich_argparse.django import DjangoRichHelpFormatter
172
from rich.console import Console
173
from rich.progress import track
174
175
class Command(BaseCommand):
176
help = """
177
Process application data with rich progress tracking.
178
179
This command demonstrates various rich-argparse features:
180
- Rich markup in help text with [bold]formatting[/bold]
181
- Progress bars using `--progress` option
182
- Colored output with `--color` option
183
- Integration with Django's command system
184
185
Examples:
186
python manage.py process_data --input data.json
187
python manage.py process_data --batch --progress
188
"""
189
190
def create_parser(self, prog_name, subcommand, **kwargs):
191
parser = super().create_parser(prog_name, subcommand, **kwargs)
192
parser.formatter_class = DjangoRichHelpFormatter
193
return parser
194
195
def add_arguments(self, parser):
196
parser.add_argument(
197
"--input",
198
type=str,
199
help="""
200
Input file path for data processing.
201
202
Supports JSON, CSV, and XML formats. The file format
203
is automatically detected based on the file extension.
204
"""
205
)
206
207
parser.add_argument(
208
"--output",
209
type=str,
210
help="Output file path (defaults to stdout)"
211
)
212
213
parser.add_argument(
214
"--format",
215
choices=["json", "csv", "xml", "yaml"],
216
default="json",
217
help="Output format for processed data"
218
)
219
220
parser.add_argument(
221
"--batch",
222
action="store_true",
223
help="""
224
Enable batch processing mode.
225
226
In batch mode, the command can process multiple input
227
files and provides progress tracking for large datasets.
228
"""
229
)
230
231
parser.add_argument(
232
"--progress",
233
action="store_true",
234
help="Show progress bar during processing"
235
)
236
237
parser.add_argument(
238
"--dry-run",
239
action="store_true",
240
help="""
241
Perform a dry run without making changes.
242
243
Shows what would be processed without actually executing
244
the data processing operations. Useful for validation.
245
"""
246
)
247
248
def handle(self, *args, **options):
249
console = Console()
250
251
if options["dry_run"]:
252
console.print("[yellow]Dry run mode - no changes will be made[/yellow]")
253
254
if options["progress"]:
255
# Simulate processing with progress bar
256
for i in track(range(100), description="Processing data..."):
257
pass
258
259
console.print("[green]Processing completed successfully![/green]")
260
```
261
262
### Built-in Command Enhancement
263
264
The richify_command_line_help function automatically enhances all Django built-in commands:
265
266
```bash
267
# All these commands will now have rich formatting
268
python manage.py help # Rich-formatted help
269
python manage.py runserver --help # Rich-formatted runserver help
270
python manage.py migrate --help # Rich-formatted migrate help
271
python manage.py collectstatic --help # Rich-formatted collectstatic help
272
```
273
274
## Advanced Configuration
275
276
### Custom Formatter Classes
277
278
```python
279
from rich_argparse.django import DjangoRichHelpFormatter, richify_command_line_help
280
from rich_argparse import RichHelpFormatter
281
282
class CustomDjangoFormatter(DjangoRichHelpFormatter):
283
"""Custom Django formatter with project-specific styling."""
284
285
styles = {
286
**DjangoRichHelpFormatter.styles,
287
"argparse.args": "bold blue",
288
"argparse.groups": "bold yellow",
289
"argparse.help": "bright_white",
290
"argparse.metavar": "bold green"
291
}
292
293
# Custom group name formatting
294
group_name_formatter = str.upper
295
296
# Custom highlight patterns
297
highlights = [
298
*RichHelpFormatter.highlights,
299
r"(?P<args>\bmanage\.py\b)", # Highlight manage.py
300
r"(?P<syntax>\b(?:True|False|None)\b)" # Highlight Python literals
301
]
302
303
# Apply custom formatter project-wide
304
richify_command_line_help(formatter_class=CustomDjangoFormatter)
305
```
306
307
### Conditional Rich Formatting
308
309
```python
310
# Enable rich formatting only in development
311
import os
312
from rich_argparse.django import richify_command_line_help
313
314
if os.environ.get("DJANGO_DEBUG", "False").lower() == "true":
315
richify_command_line_help()
316
```
317
318
## Compatibility and Limitations
319
320
### Compatibility
321
322
- **Django versions**: Compatible with Django 2.2+
323
- **Python versions**: Supports Python 3.8+
324
- **Command types**: Works with all Django command types (BaseCommand, LabelCommand, NoArgsCommand)
325
- **Third-party commands**: Automatically enhances third-party Django commands
326
- **Custom commands**: Full support for custom command implementations
327
328
### Limitations
329
330
- **Override behavior**: Commands that explicitly set their own formatter_class will not be affected by richify_command_line_help()
331
- **Import requirement**: Django must be installed and available for the django module to work
332
- **Performance**: Minimal performance overhead from rich formatting
333
334
### Error Handling
335
336
```python
337
# Safe import with fallback
338
try:
339
from rich_argparse.django import richify_command_line_help
340
richify_command_line_help()
341
except ImportError:
342
# Django not available or rich-argparse not installed
343
pass
344
```