Django
Contents
PostHog makes it easy to get data about traffic and usage of your Django app. Integrating PostHog enables analytics, custom events capture, feature flags, and more.
This guide walks you through integrating PostHog into your Django app using the Python SDK.
Installation
To start, run pip install posthog
to install PostHog’s Python SDK.
Then, set the PostHog API key and host in your AppConfig
in your your_app/apps.py
so that's it's available everywhere:
You can find your project API key and instance address in your project settings.
Next, if you haven't done so already, make sure you add your AppConfig
to your settings.py
under INSTALLED_APPS
:
Lastly, to access PostHog in any file, simply import posthog
and call the method you'd like. For example, to capture an event:
Django contexts middleware
The Python SDK provides a Django middleware that automatically wraps all requests with a context. This middleware extracts session and user information from request headers and tags all events captured during the request with relevant metadata.
Basic setup
Add the middleware to your Django settings:
The middleware automatically extracts and uses:
- Session ID from the
X-POSTHOG-SESSION-ID
header, if present - Distinct ID from the
X-POSTHOG-DISTINCT-ID
header, if present - Current URL as
$current_url
- Request method as
$request_method
All events captured during the request (including exceptions) will include these properties and be associated with the extracted session and distinct ID.
If you are using PostHog on your frontend, the JavaScript Web SDK will add the session and distinct ID headers automatically if you enable tracing headers.
Exception capture
By default, the middleware captures exceptions and sends them to PostHog's error tracking. Disable this by setting:
Adding custom tags
Use POSTHOG_MW_EXTRA_TAGS
to add custom properties to all requests:
Filtering requests
Skip tracking for certain requests using POSTHOG_MW_REQUEST_FILTER
:
Modifying default tags
Use POSTHOG_MW_TAG_MAP
to modify or remove default tags:
Complete configuration example
All events captured within the request context automatically include the configured tags and are associated with the session and user identified from the request headers.
Next steps
For any technical questions for how to integrate specific PostHog features into Django (such as analytics, feature flags, A/B testing, etc.), have a look at our Python SDK docs.
Alternatively, the following tutorials can help you get started: