--- title: Django caseStyle: snake_case supportLevel: production description: "Learn how to set up Sentry in your Django app, capture your first events and traces, and view them in Sentry." --- ## Prerequisites You need: - A Sentry [account](https://sentry.io/signup/) and [project](/product/projects/) - 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+) ## Install 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`. ## Configure **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](#send-logs) and [#4](#send-application-metrics-). This guide also enables **Tracing** and **Profiling**. ### Initialize the Sentry SDK 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: - Collection of user data, such as the user's IP address: via `data_collection` - Tracing: via `traces_sample_rate` - Profiling: via `profile_session_sample_rate` and `profile_lifecycle` Don't need a feature? Remove its options from the snippet. ```python {filename:settings.py} 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 there is an active span. profile_lifecycle="trace", ) ``` To further customize your setup, review the [Options section](#options) below. ### Capturing Errors 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`, user data (such as current user ID, email address, username) will be attached to error events. Turn this off by setting `user_info` to `False` in the `data_collection` option. In SDK versions prior to `3.0`, user data is only attached if you enable `user_info` in `data_collection` or set `send_default_pii=True`. - Request data will be attached to all events: **HTTP method, URL, headers, form data, JSON payloads**. Sentry excludes raw bodies and multipart file uploads. - If you add the [Logging](/platforms/python/integrations/logging/) integration, logs emitted by any logger will be recorded as breadcrumbs. In SDK versions prior to `3.0`, the Logging integration is enabled by default. To learn how to manually report issues, see Capturing Errors. ### Instrumenting Your App 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. ## Send Logs 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 as Sentry logs, add the corresponding integration to your `integrations`. See the standard logging and Loguru integration guides. See Set Up Logs for all available logging methods and formatting options. ```python 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"}) ``` ## Send Application Metrics 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. ```python 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") ``` ## Verify Your Setup 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: ```python from django.urls import path def trigger_error(request): 1 / 0 urlpatterns = [path("sentry-debug/", trigger_error)] ``` ### View Captured Data in Sentry Now, head over to your project on [Sentry.io](https://sentry.io) to view the collected data (it takes a couple of moments for the data to appear). ## Options Add `DjangoIntegration` explicitly to your `sentry_sdk.init()` call to set options for `DjangoIntegration` to change its behavior: ```python import django.db.models.signals import sentry_sdk from sentry_sdk.integrations.django import DjangoIntegration sentry_sdk.init( # ... integrations=[ DjangoIntegration( 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()`: Only available in SDK versions prior to `3.0`. In SDK `3.x`, service spans are always named after the route pattern, for example `/myproject/myview/`. How to name transactions that show up in Sentry tracing. - `"/myproject/myview/"` if you set `transaction_style="url"`. - `"myproject.myview"` if you set `transaction_style="function_name"`. The default is `"url"`. Create spans and track performance of all middleware layers in your Django project. Set to `True` to enable. The default is `False`. Create spans and track performance of all synchronous [Django signals](https://docs.djangoproject.com/en/dev/topics/signals/) receiver functions in your Django project. Set to `False` to disable. The default is `True`. A list of signals to exclude from performance tracking. No spans will be created for these. The default is `[]`. 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 `False` to disable. The default is `True`. In SDK versions prior to `3.0`, the default is `False`. A tuple containing all the HTTP methods (as uppercase strings) that should create a service span in Sentry. The default is `("CONNECT", "DELETE", "GET", "PATCH", "POST", "PUT", "TRACE",)`. Note that `OPTIONS` and `HEAD` are excluded by default. 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. ## Next Steps At this point, you should have integrated Sentry into your Django application. Here's what to explore next: - Explore [practical guides](/get-started/guides/) on what to monitor, log, track, and investigate after setup - Set up Agent Tracing to follow agent runs from system prompt to final output, capturing every model call, tool execution, and handoff as a span - Learn how to manually capture errors - Find various topics in Troubleshooting - [Get support](https://www.sentry.help/en/)