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

To easily track your Docusaurus site, you can install the PostHog plugin . This enables you to autocapture pageviews, clicks, session replays, as well as use the other features of PostHog such as surveys . Install Once you have your Docusaurus site set up, install the PostHog plugin: or Next, add it to your Docusaurus config with your project API key and instance address, both of which you can find in your project settings . Run your site again to see events autocaptured by PostHog. Note…

Read next article