Django

Last updated:

|Edit this page

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:

your_app/apps.py
from django.apps import AppConfig
import posthog
class YourAppConfig(AppConfig):
name = "your_app_name"
def ready(self):
posthog.api_key = '<ph_project_api_key>'
posthog.host = https://us.i.posthog.com

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:

settings.py
INSTALLED_APPS = [
# other apps
'your_app_name.apps.MyAppConfig', # Add your app config
]

Lastly, to access PostHog in any file, simply import posthog and call the method you'd like. For example, to capture an event:

Python
import posthog
def some_request(request):
posthog.capture('distinct_id_of_the_user', 'event_name')

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:

Questions?

Was this page useful?

Next article

Docusaurus

This is a community integration that is not maintained by the PostHog core team. Install or How to use This will automatically start tracking pageviews, clicks and more. For more instructions, see the browser JS library .

Read next article