Django for Python

Learn how to set up Sentry in your Django app, capture your first events and traces, and view them in Sentry.

You need:

  • A Sentry account and project
  • Your application up and running
  • Django:
    • 1.8+ (SDK <3.0)
    • 2.0+ (SDK 3.0+)
  • Python:
    • 3.6+ (SDK <3.0)
    • 3.7+ (SDK 3.0+)

Run the command for your preferred package manager to add the Sentry SDK to your application:

Copied
pip install "sentry-sdk"

This guide requires sentry-sdk version 2.70.0 or later. If you already have the SDK installed, upgrade it with pip install --upgrade sentry-sdk.

Error Monitoring starts working as soon as you call sentry_sdk.init(). Logs and Application Metrics need no extra configuration when using sentry_sdk.logger and sentry_sdk.metrics, and you'll learn how to send them in steps #3 and #4. This guide also enables Tracing and Profiling.

Want to learn more about these features?
  • Issues (always enabled): Sentry's core error monitoring product that automatically reports errors, uncaught exceptions, and crashes. If you have something that looks like an exception, Sentry can capture it.
  • Tracing: Track software performance while seeing the impact of errors across multiple systems. For example, distributed tracing allows you to follow a request from the frontend to the backend and back.
  • Profiling: Gain deeper insight than traditional tracing without custom instrumentation, letting you discover slow-to-execute or resource-intensive functions in your app.
  • Logs: Centralize and analyze your application logs to correlate them with errors and performance issues. Search, filter, and visualize log data to understand what's happening in your applications.
  • Application Metrics (always enabled): Track and analyze custom application metrics, such as response times and database query durations, to understand trends and patterns in your application's performance and behavior over time.

Configuration should happen as early as possible in your application's lifecycle.

To configure the Sentry SDK, initialize it in your settings.py file:

The snippet also turns on:

Don't need a feature? Remove its options from the snippet.

settings.py
Copied
import sentry_sdk

sentry_sdk.init(
    dsn="___PUBLIC_DSN___",
    # Check https://docs.sentry.io/platforms/python/data-management/data-collected/ to configure what data is collected
    data_collection={
        "user_info": True,
    },
    # Enables Tracing.
    # Set to 1.0 to capture 100% of spans for tracing.
    # We recommend reducing this value in production.
    traces_sample_rate=1.0,
    # Enables Profiling.
    # Set to 1.0 to profile 100% of sessions.
    profile_session_sample_rate=1.0,
    # Profiles are collected while a transaction is active.
    profile_lifecycle="trace",
)

To further customize your setup, review the Options section below.

Sentry automatically captures errors and reports issues for you. You can also expect the following for your Django project:

  • If you use django.contrib.auth, and you've either enabled user_info in the data_collection option or set send_default_pii=True in your call to init, user data (such as current user ID, email address, username) will be attached to error events. send_default_pii will be removed in version 3.0 of the SDK.
  • Request data will be attached to all events: HTTP method, URL, headers, form data, JSON payloads. Sentry excludes raw bodies and multipart file uploads.
  • Logs emitted by any logger will be recorded as breadcrumbs by the Logging integration (this integration is enabled by default).

To learn how to manually report issues, see Capturing Errors.

Are you using uWSGI?

If you're using uWSGI, note that it doesn't support threads by default. This might lead to unexpected behavior when using the Sentry SDK, from features not working properly to uWSGI workers crashing.

To enable threading support in uWSGI, make sure you have both --enable-threads and --py-call-uwsgi-fork-hooks on.

Note that automatic tracing on file-like responses when offloading is configured is disabled (see here for why). If you wish to enable tracing on these types of responses, you will need to manually instrument them.

The Sentry SDK automatically monitors the following parts of your Django project:

  • Middleware stack
  • Signals
  • Database queries
  • Redis commands
  • Access to Django caches

You can also manually capture performance data – see Custom Instrumentation to learn more.

Use sentry_sdk.logger to send structured logs at different levels. You can include searchable attributes with each message.

To capture records from Python's standard-library logging module or Loguru, configure capture_sentry_logs=True on the corresponding integration. See the standard logging and Loguru integration guides.

See Set Up Logs for all available logging methods and formatting options.

Copied
import sentry_sdk

sentry_sdk.logger.info("Order processed {order_id}", order_id="order-123")
sentry_sdk.logger.warning("Rate limit reached", attributes={"endpoint": "/api/orders"})

Use sentry_sdk.metrics to send counters, gauges, and distributions from your app. Metrics are enabled by default after you initialize the SDK.

See Set Up Metrics for all available metric types and configuration options.

Copied
import sentry_sdk

sentry_sdk.metrics.count("checkout.failed", 1)
sentry_sdk.metrics.gauge("active_connections", 42)
sentry_sdk.metrics.distribution("api_latency", 187, unit="millisecond")

Let's test your setup and confirm that data reaches your Sentry project.

Add a view that raises an exception and route it in your Django application:

Copied
from django.urls import path

def trigger_error(request):
    1 / 0

urlpatterns = [path("sentry-debug/", trigger_error)]

Now, head over to your project on Sentry.io to view the collected data (it takes a couple of moments for the data to appear).

Need help locating captured data in your Sentry project?
  • Open the Issues page and select an error from the issues list to view the full details and context of this error. For more details, see the Issue Details documentation.
  • Open the Traces page and select a trace to reveal more information about each span, its duration, and any errors. For an interactive UI walkthrough, click here.
  • Open the Profiles page to see your slowest functions and an aggregate flame graph of your most frequent code paths. If tracing is enabled, select a transaction to see the flame graph for that part of your app. For more information, click here.
  • Open the Logs page and filter by service, environment, or search keywords to view log entries from your application. For an interactive UI walkthrough, click here.
  • Open the Application Metrics page to view and analyze your metrics. For more details, see this interactive walkthrough.

Add DjangoIntegration explicitly to your sentry_sdk.init() call to set options for DjangoIntegration to change its behavior:

Copied
import django.db.models.signals

import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration

sentry_sdk.init(
    # ...
    integrations=[
        DjangoIntegration(
            transaction_style='url',
            middleware_spans=True,
            signals_spans=True,
            signals_denylist=[
                django.db.models.signals.pre_init,
                django.db.models.signals.post_init,
            ],
            cache_spans=False,
            http_methods_to_capture=("GET",),
        ),
    ],
)

You can pass the following keyword arguments to DjangoIntegration():

transaction_style

Typestring
Default"url"

How to name transactions that show up in Sentry tracing.

  • "/myproject/myview/<foo>" if you set transaction_style="url".
  • "myproject.myview" if you set transaction_style="function_name".

The default is "url".

middleware_spans

Typebool
DefaultFalse

Create spans and track performance of all middleware layers in your Django project. Set to True to enable. The default is False.

signals_spans

Typebool
DefaultTrue

Create spans and track performance of all synchronous Django signals receiver functions in your Django project. Set to False to disable. The default is True.

signals_denylist

Typelist[Signal]
Default[]

A list of signals to exclude from performance tracking. No spans will be created for these. The default is [].

cache_spans

Typebool
DefaultFalse

Create spans and track performance of all read operations to configured caches. The spans also include information if the cache access was a hit or a miss. Set to True to enable. The default is False.

http_methods_to_capture

Available since2.15.0
TypeTuple[str, ...]
Default("CONNECT", "DELETE", "GET", "PATCH", "POST", "PUT", "TRACE",)

A tuple containing all the HTTP methods (as uppercase strings) that should create a transaction in Sentry. The default is ("CONNECT", "DELETE", "GET", "PATCH", "POST", "PUT", "TRACE",).

Note that OPTIONS and HEAD are excluded by default.

failed_request_status_codes

Typeset[int]
Default{*range(500, 600)}

A set of integers that will determine which status codes should be reported to Sentry.

The failed_request_status_codes option determines whether exceptions handled within Django should be reported to Sentry. Unhandled exceptions that don't have a status_code attribute will always be reported to Sentry.

Examples of valid failed_request_status_codes:

  • {500} will only send events on HTTP 500.
  • {400, *range(500, 600)} will send events on HTTP 400 as well as the 5xx range.
  • {500, 503} will send events on HTTP 500 and 503.
  • set() (the empty set) will not send events for any HTTP status code.

The default is {*range(500, 600)}, meaning that all 5xx status codes are reported to Sentry.

At this point, you should have integrated Sentry into your Django application. Here's what to explore next:

Are you having problems setting up the SDK?
Was this helpful?
Help improve this content
Our documentation is open source and available on GitHub. Your contributions are welcome, whether fixing a typo (drat!) or suggesting an update ("yeah, this would be better").