0
# Management Commands
1
2
Django Extensions provides 44+ management commands that extend Django's built-in management system with powerful utilities for development, debugging, database operations, and administrative tasks. All commands are accessed via Django's manage.py: `python manage.py <command_name>`.
3
4
## Capabilities
5
6
### Development Commands
7
8
Commands that enhance the development workflow with improved shells, servers, and debugging tools.
9
10
```python { .api }
11
# Enhanced shell with auto-imported models and utilities
12
def shell_plus():
13
"""
14
Like Django's 'shell' command but autoloads models of all installed Django apps.
15
16
Options:
17
--plain: Use plain Python interpreter instead of IPython/bpython
18
--ipython: Force IPython interpreter
19
--bpython: Force bpython interpreter
20
--notebook: Start Jupyter notebook with Django context
21
--kernel: Install Django kernel for Jupyter
22
--print-sql: Print SQL queries to stdout
23
"""
24
25
# Enhanced development server with debugging features
26
def runserver_plus():
27
"""
28
Starts enhanced development server with Werkzeug debugging capabilities.
29
30
Options:
31
--reloader-type: Type of reloader (auto, stat, watchdog)
32
--keep-meta-shutdown: Keep SHUTDOWN_MESSAGE meta variable
33
--nopin: Disable PIN-based authentication for debugger
34
"""
35
36
# Development server with profiling enabled
37
def runprofileserver():
38
"""
39
Starts lightweight web server with profiling enabled.
40
41
Options:
42
--prof-path: Directory to store profile files
43
--prof-file: Filename for profile output
44
--nomedia: Don't profile MEDIA_URL files
45
--use-lsprof: Use lsprof for profiling
46
"""
47
48
# Test mail server for development
49
def mail_debug():
50
"""
51
Starts a test mail server for development that prints emails to console.
52
53
Options:
54
--output: Output format (console, file)
55
--port: Port number (default: 1025)
56
"""
57
```
58
59
### Code Generation Commands
60
61
Commands that generate boilerplate code and project structure.
62
63
```python { .api }
64
# Generate admin.py file for models
65
def admin_generator():
66
"""
67
Generate admin.py file for the given app models.
68
69
Args:
70
app_name: Name of Django app
71
72
Options:
73
--print: Print to stdout instead of writing file
74
"""
75
76
# Create management command structure
77
def create_command():
78
"""
79
Creates Django management command directory structure.
80
81
Args:
82
app_name: Name of Django app
83
command_name: Name of management command
84
"""
85
86
# Create jobs directory structure
87
def create_jobs():
88
"""
89
Creates Django jobs command directory structure.
90
91
Args:
92
app_name: Name of Django app
93
"""
94
95
# Create template tags structure
96
def create_template_tags():
97
"""
98
Creates Django template tags directory structure.
99
100
Args:
101
app_name: Name of Django app
102
template_tag_name: Name of template tag library
103
"""
104
```
105
106
### Database Commands
107
108
Commands for database operations, analysis, and management.
109
110
```python { .api }
111
# Reset database completely
112
def reset_db():
113
"""
114
Resets the database for this project.
115
116
Options:
117
--noinput: Don't prompt for confirmation
118
--router: Database router to use
119
--close-sessions: Close database sessions before reset
120
"""
121
122
# Generate SQL for database creation
123
def sqlcreate():
124
"""
125
Generates SQL to create database as specified in settings.py.
126
127
Options:
128
--router: Database router to use
129
"""
130
131
# Show differences between models and database
132
def sqldiff():
133
"""
134
Prints approximated difference between models and database fields.
135
136
Args:
137
app_names: Names of apps to analyze (optional)
138
139
Options:
140
--all-applications: Check all installed applications
141
--not-only-existing: Include non-existing tables
142
"""
143
144
# Export database as Python script
145
def dumpscript():
146
"""
147
Dumps data as customized Python script.
148
149
Args:
150
app_names: Names of apps to dump (optional)
151
152
Options:
153
--stdout: Output to stdout instead of file
154
--format: Output format (python, json, xml, yaml)
155
"""
156
157
# Show differences between models and database
158
def sqldiff():
159
"""
160
Prints approximated difference between models and database fields.
161
162
Args:
163
app_names: Names of apps to analyze (optional)
164
165
Options:
166
--all-applications: Check all installed applications
167
--not-only-existing: Include non-existing tables
168
"""
169
170
# Sync data to match fixtures exactly
171
def syncdata():
172
"""
173
Makes database have same data as fixtures, no more, no less.
174
175
Args:
176
fixture_names: Names of fixture files
177
178
Options:
179
--skip-remove: Don't remove objects not in fixtures
180
"""
181
182
# Drop test database
183
def drop_test_database():
184
"""
185
Drops test database for this project.
186
187
Options:
188
--noinput: Don't prompt for confirmation
189
"""
190
191
# Manage database state
192
def managestate():
193
"""
194
Manage database state in convenient way.
195
196
Options:
197
--list: List available states
198
--save: Save current state
199
--load: Load saved state
200
"""
201
202
# Merge duplicate model instances
203
def merge_model_instances():
204
"""
205
Removes duplicate model instances based on specified field.
206
207
Args:
208
model_name: Name of model to process
209
field_name: Field to check for duplicates
210
211
Options:
212
--noinput: Don't prompt for confirmation
213
"""
214
```
215
216
### Analysis Commands
217
218
Commands for analyzing and inspecting Django projects.
219
220
```python { .api }
221
# Generate model relationship diagrams
222
def graph_models():
223
"""
224
Creates GraphViz dot file for specified app names.
225
226
Args:
227
app_names: Names of apps to include (optional)
228
229
Options:
230
--output: Output file path
231
--layout: Graph layout (dot, neato, fdp, sfdp, twopi, circo)
232
--theme: Graph theme (original, django2018)
233
--group-models: Group models by application
234
--all-applications: Include all installed applications
235
--include-models: Comma-separated list of models to include
236
--exclude-models: Comma-separated list of models to exclude
237
"""
238
239
# Display URL patterns
240
def show_urls():
241
"""
242
Displays all URL matching routes for the project.
243
244
Options:
245
--urlconf: Specify URLconf module
246
--format: Output format (dense, table, aligned, vertical)
247
--decorator: Show view decorators
248
--language: Show for specific language
249
"""
250
251
# List model information
252
def list_model_info():
253
"""
254
List fields and methods for each model.
255
256
Args:
257
app_names: Names of apps to analyze (optional)
258
"""
259
260
# Show template tags and filters
261
def show_template_tags():
262
"""
263
Displays template tags and filters available in current project.
264
265
Options:
266
--show-builtins: Include built-in template tags
267
"""
268
269
# Find template location
270
def find_template():
271
"""
272
Finds location of given template by resolving its path.
273
274
Args:
275
template_name: Name of template to find
276
"""
277
278
# List Django signals
279
def list_signals():
280
"""
281
List all signals by model and signal type.
282
283
Args:
284
app_names: Names of apps to analyze (optional)
285
"""
286
287
# Show code annotations (TODO, FIXME, etc.)
288
def notes():
289
"""
290
Show annotations like TODO, FIXME, BUG, HACK, WARNING, NOTE, XXX.
291
292
Options:
293
--tag: Specific annotation tag to search for
294
"""
295
296
# Check pip requirements for updates
297
def pipchecker():
298
"""
299
Scan pip requirement files for out-of-date packages.
300
301
Options:
302
--requirements: Path to requirements file
303
--github-token: GitHub token for API access
304
"""
305
306
# Find unreferenced media files
307
def unreferenced_files():
308
"""
309
Prints list of files in MEDIA_ROOT not referenced in database.
310
311
Options:
312
--media-root: Override MEDIA_ROOT setting
313
"""
314
315
# Validate templates for syntax errors
316
def validate_templates():
317
"""
318
Validate templates for syntax and compile errors.
319
320
Args:
321
app_names: Names of apps to validate (optional)
322
"""
323
324
# Update model permissions
325
def update_permissions():
326
"""
327
Reloads permissions for specified apps or all apps.
328
329
Args:
330
app_names: Names of apps to update (optional)
331
"""
332
333
# Print database DSN
334
def sqldsn():
335
"""
336
Prints database DSN as specified in settings.py.
337
338
Options:
339
--router: Database router to use
340
"""
341
```
342
343
### Utility Commands
344
345
Utility commands for common development tasks.
346
347
```python { .api }
348
# Print Django settings
349
def print_settings():
350
"""
351
Print active Django settings.
352
353
Options:
354
--format: Output format (text, json, yaml)
355
--indent: Indentation for formatted output
356
"""
357
358
# Generate random password
359
def generate_password():
360
"""
361
Generates new password using Django's default password generator.
362
363
Options:
364
--length: Password length (default: 10)
365
"""
366
367
# Generate secret key
368
def generate_secret_key():
369
"""
370
Generates new SECRET_KEY for Django settings.
371
372
Options:
373
--length: Key length (default: 50)
374
"""
375
376
# Clean Python bytecode files
377
def clean_pyc():
378
"""
379
Removes all Python bytecode compiled files from project.
380
381
Options:
382
--optimize: Also remove .pyo files
383
--path: Specific path to clean
384
"""
385
386
# Compile Python bytecode files
387
def compile_pyc():
388
"""
389
Compile Python bytecode files for the project.
390
391
Options:
392
--path: Specific path to compile
393
"""
394
395
# Clear Django cache
396
def clear_cache():
397
"""
398
Fully clear site-wide cache.
399
400
Options:
401
--cache: Specific cache to clear
402
"""
403
404
# Run maintenance jobs
405
def runjobs():
406
"""
407
Runs scheduled maintenance jobs.
408
409
Args:
410
frequency: Job frequency (hourly, daily, weekly, monthly, yearly)
411
412
Options:
413
--list: List available jobs
414
"""
415
416
# Run single maintenance job
417
def runjob():
418
"""
419
Run single maintenance job.
420
421
Args:
422
job_name: Name of job to run
423
"""
424
425
# Run Python script in Django context
426
def runscript():
427
"""
428
Runs Python script in Django context.
429
430
Args:
431
script_name: Name of script to run
432
433
Options:
434
--script-args: Arguments to pass to script
435
"""
436
437
# Set default site parameters
438
def set_default_site():
439
"""
440
Set parameters of default django.contrib.sites Site.
441
442
Options:
443
--system-fqdn: Use system FQDN
444
--name: Site name
445
--domain: Site domain
446
"""
447
448
# Export user emails
449
def export_emails():
450
"""
451
Export user email addresses in various formats.
452
453
Options:
454
--format: Output format (address, name_email, json)
455
--output: Output file path
456
"""
457
458
# Print user for session
459
def print_user_for_session():
460
"""
461
Print user information for provided session key.
462
463
Args:
464
session_key: Django session key
465
"""
466
467
# Validate templates
468
def validate_templates():
469
"""
470
Validate templates for syntax and compile errors.
471
472
Args:
473
app_names: Names of apps to validate (optional)
474
"""
475
476
# Update model permissions
477
def update_permissions():
478
"""
479
Reloads permissions for specified apps or all apps.
480
481
Args:
482
app_names: Names of apps to update (optional)
483
"""
484
485
# Raise test exception
486
def raise_test_exception():
487
"""
488
Raises test Exception named DjangoExtensionsTestException.
489
490
Used for testing error handling and logging.
491
"""
492
493
# Describe form from model
494
def describe_form():
495
"""
496
Outputs specified model as form definition to shell.
497
498
Args:
499
model_name: Name of model to describe
500
"""
501
502
# Set fake user emails (DEBUG only)
503
def set_fake_emails():
504
"""
505
DEBUG only: Give all users new email based on account data.
506
507
Args:
508
email_template: Email template (default: "%s@example.com")
509
"""
510
511
# Set fake user passwords (DEBUG only)
512
def set_fake_passwords():
513
"""
514
DEBUG only: Sets all user passwords to common value.
515
516
Args:
517
password: Password to set for all users
518
"""
519
520
# Sync media files to S3
521
def sync_s3():
522
"""
523
Syncs complete MEDIA_ROOT structure and files to S3 bucket.
524
525
Args:
526
bucket_name: Name of S3 bucket
527
528
Options:
529
--aws-access-key-id: AWS access key ID
530
--aws-secret-access-key: AWS secret access key
531
--prefix: S3 key prefix
532
"""
533
534
# Delete squashed migrations
535
def delete_squashed_migrations():
536
"""
537
Deletes migrations replaced by squashed migration.
538
539
Options:
540
--noinput: Don't prompt for confirmation
541
"""
542
543
# Reset database schema
544
def reset_schema():
545
"""
546
Recreates public schema for this project.
547
548
Options:
549
--noinput: Don't prompt for confirmation
550
"""
551
552
# Print database DSN
553
def sqldsn():
554
"""
555
Prints database DSN as specified in settings.py.
556
557
Options:
558
--router: Database router to use
559
"""
560
```
561
562
## Usage Examples
563
564
```python
565
# Enhanced shell with all models imported
566
python manage.py shell_plus
567
568
# Show all URL patterns in a table format
569
python manage.py show_urls --format=table
570
571
# Generate model diagram for specific apps
572
python manage.py graph_models myapp anotherapp --output=models.png
573
574
# Reset database (be careful!)
575
python manage.py reset_db --noinput
576
577
# Export data as Python script
578
python manage.py dumpscript myapp > data_export.py
579
580
# Check for code annotations
581
python manage.py notes
582
583
# Generate a new secret key
584
python manage.py generate_secret_key
585
586
# Run the enhanced development server
587
python manage.py runserver_plus
588
589
# Profile the development server
590
python manage.py runprofileserver --prof-path=/tmp/profiles/
591
```