SDK & Framework Guides

Django Error Monitoring with the Sentry SDK

Replace Django's email error reports with real-time, grouped error tracking. Add the Sentry SDK, capture request context, and tag releases.

Django's default error reporting — an email when something breaks — works fine for one-person shops but falls apart at scale. A deployed celery task silently crashes. An API endpoint 500s for 2% of requests. A race condition that only happens on Tuesdays. Without proper error tracking, these bugs discover you instead of the other way around. Django error tracking with the Sentry SDK replaces Django's email reports with real-time grouped errors, breadcrumbs, and the context needed to debug production failures in minutes.

This guide walks you through adding the Sentry SDK to a Django app, wiring it into Django's error handlers, capturing request context, and shipping readable stack traces that link back to your source. By the end, errors that would have silently failed or arrived as a vague email will instead be grouped, prioritized, and ready to fix.

Install and initialize the SDK

Start by adding the Sentry SDK package:

pip install sentry-sdk

Initialize the SDK in your Django settings, before anything imports your views or models:

# settings.py
import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration

sentry_sdk.init(
    dsn="https://<key>@your-lighttrace-host/1",
    integrations=[DjangoIntegration()],
    environment="production",
    release="api@1.4.2",
    traces_sample_rate=1.0,
)

The DjangoIntegration() installs middleware that automatically captures:

  • Every unhandled exception in views, signals, and middleware
  • HTTP request details (method, path, query params, headers)
  • Response status codes
  • Database query spans (if you enable performance monitoring)
  • Breadcrumbs for Django logging

That initialization is all it takes. Errors now flow to LightTrace instead of to your inbox.

Set traces_sample_rate=1.0 to capture all transactions for development and testing. In production on a high-traffic app, you can lower this to 0.1 or 0.01 to reduce event volume while still catching performance issues.

Attach request and user context

Raw errors are a start, but context makes debugging fast. Set the user whenever you authenticate a request, and add breadcrumbs at key moments:

# views.py
import sentry_sdk

def login(request):
    # ... authenticate user ...
    if user_authenticated:
        sentry_sdk.set_user({"id": user.id, "email": user.email})

def checkout(request):
    sentry_sdk.add_breadcrumb(
        category="checkout",
        message="User clicked place order",
        level="info",
    )
    # ... process payment ...

Now every error that happens after login includes the user's ID and email. Every error after a checkout breadcrumb includes the breadcrumb trail leading to the failure. The combination of stack trace + breadcrumbs + user info cuts debugging time from hours to minutes.

You can also set custom tags and contexts for any error:

sentry_sdk.set_tag("database", "primary")
sentry_sdk.set_context("checkout", {"cart_items": 5, "total_cents": 19999})

Tags let you filter issues in the LightTrace dashboard; contexts give you rich debugging data when you open an issue.

Handle async tasks and background jobs

Celery tasks and other background work need explicit error handling. Wrap task execution to report failures to LightTrace:

# tasks.py
from celery import shared_task
import sentry_sdk

@shared_task
def send_email_reminder(user_id):
    try:
        user = User.objects.get(id=user_id)
        send_email(user)
    except Exception as e:
        sentry_sdk.capture_exception(e)
        raise

For more complex scenarios, use Sentry's Celery integration:

# settings.py
from sentry_sdk.integrations.celery import CeleryIntegration

sentry_sdk.init(
    dsn="...",
    integrations=[DjangoIntegration(), CeleryIntegration()],
)

With the Celery integration, background job failures are automatically captured along with the task name, args, and status — no manual wrapping needed.

Track releases and deploy health

Tag each event with the release so you can see which deploy introduced a regression:

# settings.py
import os

sentry_sdk.init(
    dsn="...",
    release=f"api@{os.getenv('APP_VERSION', '1.0.0')}",
    environment=os.getenv("ENVIRONMENT", "production"),
)

Include the version and environment as part of your release string (e.g., api@1.4.2). When you deploy a new version, every error arriving afterward is tagged with that release. If a release's error rate spikes, you know immediately that the new code caused it, and you can triage quickly to decide whether to roll back or fix forward.

Set the environment variable to match your deployment stage (production, staging, development). This lets you filter errors by environment in the LightTrace dashboard so staging noise doesn't hide production bugs.

Make stack traces readable with source maps

If you're running Django with a JavaScript frontend (React, Vue, etc.), errors can come from both the backend and the browser. Django errors are readable by default, but JavaScript errors need source maps to be useful. See upload source maps for the full guide; the pattern is the same — generate maps during build, upload them during CI.

Common Django errors to watch

A few Django-specific errors show up constantly in production:

  • 500 Server Error — an unhandled exception in a view; LightTrace groups identical ones so you see the issue count.
  • Database connection failures — usually transient, but if they spike, it's a real problem. LightTrace alerts you if a new issue appears.
  • Signal handler crashes — errors in post_save, pre_delete, and other signal handlers are easy to miss; Sentry's Django integration catches them automatically.
  • Middleware exceptions — if your middleware raises an exception, it normally bypasses error logging. The integration handles this too.

Each becomes a grouped issue with a stack trace and user count, making it actionable instead of mysterious.

Scrub sensitive data before it leaves your server

Django apps often handle sensitive data — passwords, API keys, credit card tokens, PII. These can leak into error reports if you're not careful. The Sentry SDK has built-in sensitive data scrubbing that removes passwords and common private fields automatically. You can extend it:

# settings.py
sentry_sdk.init(
    dsn="...",
    integrations=[DjangoIntegration()],
    # Remove custom fields before sending
    before_send=lambda event, hint: event if event.get("request", {}).get("headers", {}).get("authorization") is None else (event.update({"request": {**event.get("request", {}), "headers": {**event.get("request", {}).get("headers", {}), "authorization": "[redacted]"}}}), event)[1],
)

Or use the simpler declarative approach with patterns_re:

import sentry_sdk

sentry_sdk.init(
    dsn="...",
    integrations=[DjangoIntegration()],
    before_send=lambda event, hint: (
        sentry_sdk.integrations.django.DjangoIntegration.before_send(event, hint)
        if hasattr(sentry_sdk.integrations.django.DjangoIntegration, 'before_send')
        else event
    ),
)

The point: errors are only useful if they're safe to store. LightTrace keeps your data private while giving you the context you need.

Test it locally

Before deploying, verify the SDK is working by triggering a fake error:

# views.py
def test_error(request):
    if request.GET.get("trigger"):
        1 / 0  # Intentional error
    return HttpResponse("Test page")

Visit /test-error/?trigger=1, and after a moment you should see the error appear in your LightTrace dashboard. Delete the test view once you've confirmed.

Start tracking errors in minutes

Add the Sentry SDK to your Django app and capture grouped errors in minutes — start free with up to 5,000 events a month.

Production Django apps face errors constantly — the question is whether you know about them. Real-time error tracking with LightTrace means you spot failures in your dashboard before customers do. You get a shorter MTTR because you have the stack trace, the user, the breadcrumbs, and the release context all in one place. The setup is simple — a few lines in settings.py, a few decorators where you need them — and the payoff is immediate: fewer silent failures, faster debugging, and the confidence that comes from knowing your errors as they happen. For a broader look at the pattern across all frameworks, see how to add error tracking to any app.

Fix your next production error faster

Point any Sentry SDK at LightTrace — free up to 5,000 events/month.