如何将django-extensions的graph_models生成的模型图集成到Django后台文档界面?
Great question! Integrating your Django model diagrams from graph_models into django.contrib.admindocs with a streamlined command like collectstatic is totally doable—here's a practical approach:
graph_models to output to your static directory First, make sure you can generate diagrams directly into your project's static files area. Test this manually first to confirm:
python manage.py graph_models -a -o static/docs/models.png
-atargets all installed apps (replace with specific app names likemyapp1 myapp2if you don't want all models)-odefines the output path—we're putting it in adocssubfolder within your static directory so it's easy to reference in admindocs.
Django doesn't have a built-in command for this, but you can build one that works exactly like collectstatic—one command to generate and place the diagram in the right spot.
In one of your Django apps, create the directory structure:
your_app/ management/ commands/ __init__.py collect_models_graph.pyAdd this code to
collect_models_graph.py:
from django.core.management.base import BaseCommand, CommandError import subprocess import os from django.conf import settings class Command(BaseCommand): help = 'Generates and collects database model diagrams into static files for admindocs' def handle(self, *args, **options): # Set up output directory in static files output_dir = os.path.join(settings.STATIC_ROOT, 'docs') os.makedirs(output_dir, exist_ok=True) output_path = os.path.join(output_dir, 'models.png') # Run graph_models to generate the diagram try: subprocess.run( [ 'python', 'manage.py', 'graph_models', '-a', # Adjust to specific apps if needed '-o', output_path, '-g', 'dot' # Optional: specify layout engine (dot, neato, etc.) ], check=True, capture_output=True, text=True ) self.stdout.write(self.style.SUCCESS(f"✅ Model diagram saved to {output_path}")) except subprocess.CalledProcessError as e: raise CommandError(f"❌ Failed to generate diagram: {e.stderr}")
Now you can run this just like any other manage.py command:
python manage.py collect_models_graph
If you use remote static storage (like S3), run python manage.py collectstatic afterward to sync the diagram to your CDN.
To display the diagram in the admindocs interface, override the admindocs index template:
- Create a template file at
templates/admin/doc/index.html:
{% extends "admin/doc/index.html" %} {% block content %} {{ block.super }} <div class="module" style="margin-top: 20px;"> <h2>Database Model Diagram</h2> <img src="{% static 'docs/models.png' %}" alt="Full Database Model Diagram" style="max-width: 100%; height: auto;"> </div> {% endblock %}
- Make sure your
TEMPLATESsetting includes your app's templates directory so Django picks up this override.
- Graphviz Dependency: Ensure Graphviz is installed on your system (it's required for
graph_modelsto generate images). - Customization: Tweak the
graph_modelsparameters in the command to adjust diagram style, include/exclude apps, or generate multiple diagrams (e.g., per app). - Automation: Add
collect_models_graphto your deployment pipeline if you want diagrams to update automatically when models change.
内容的提问来源于stack exchange,提问作者thinwybk

