Skip to content

Instantly share code, notes, and snippets.

@adamghill
Created July 31, 2025 23:11
Show Gist options
  • Save adamghill/9aebf19fc3ce22a6609986a8bee9a858 to your computer and use it in GitHub Desktop.
Save adamghill/9aebf19fc3ce22a6609986a8bee9a858 to your computer and use it in GitHub Desktop.
Django middleware to collect basic statistics and show on a template
{% if request.user.is_superuser %}
<div class="p-4 bg-gray-100">
<div class="font-bold">
DEBUG-O-MATIC
</div>
<!-- DEBUG STATS -->
<div class="pt-2 font-bold">
Current user
</div>
<ul>
<li>Logged In: {{ request.user.is_authenticated }}</li>
<li>Logged in username: {{ request.user.username|default:'n/a' }}</li>
</ul>
<div class="pt-2 font-bold">
Request
</div>
<ul>
<li>Host: {{ request.get_host }}</li>
<li>Path: {{ request.get_full_path }}</li>
</ul>
</div>
{% endif %}
from time import time
from django.db import connection
class StatsMiddleware:
"""Based on https://github.com/bernd-wechner/django-stats-middleware."""
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
if not request.user.is_superuser:
return self.get_response(request)
if request.path.startswith("/do-not-profile-me"): # ignore certain paths
return self.get_response(request)
# Get number of db queries before we do anything
original_query_count = len(connection.queries)
# Time the view
start = time()
response = self.get_response(request)
total_time = time() - start
# Compute the query count for the queries just run
query_count = len(connection.queries) - original_query_count
stats = f"""
<div class="pt-2 font-bold">
Stats
</div>
<ul>
<li>Total Time: {total_time * 1000:.1f}ms</li>
<li>Number of Queries: {query_count:,}</li>
</ul>
"""
# Replace the stats if it's in the template
if response:
if content := getattr(response, "content", None):
response.content = content.decode().replace("<!-- DEBUG STATS -->", stats)
response["Content-Length"] = str(len(response.content))
return response
@adamghill
Copy link
Author

@djpeacher improved on this idea and made a package that I'd recommend using: https://github.com/djpeacher/django-chronos.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment