diff --git a/apps/basic-integration/django/django3-saas/.claude/skills/integration-django/.posthog-wizard b/apps/basic-integration/django/django3-saas/.claude/skills/integration-django/.posthog-wizard new file mode 100644 index 000000000..e69de29bb diff --git a/apps/basic-integration/django/django3-saas/.claude/skills/integration-django/SKILL.md b/apps/basic-integration/django/django3-saas/.claude/skills/integration-django/SKILL.md new file mode 100644 index 000000000..04b54d7b6 --- /dev/null +++ b/apps/basic-integration/django/django3-saas/.claude/skills/integration-django/SKILL.md @@ -0,0 +1,64 @@ +--- +name: integration-django +description: PostHog integration for Django applications +metadata: + author: PostHog + version: dev +--- + +# PostHog integration for Django + +This skill helps you add PostHog analytics to Django applications. + +## Workflow + +Follow these steps in order to complete the integration: + +1. `references/1-begin.md` - PostHog Setup - Begin ← **Start here** +2. `references/2-edit.md` - PostHog Setup - Edit +3. `references/3-revise.md` - PostHog Setup - Revise +4. `references/4-conclude.md` - PostHog Setup - Conclusion + +## Reference files + +- `references/EXAMPLE.md` - Django example project code +- `references/1-begin.md` - Start the event tracking setup process by analyzing the project and creating an event tracking plan +- `references/2-edit.md` - Implement PostHog event tracking in the identified files, following best practices and the example project +- `references/3-revise.md` - Review and fix any errors in the PostHog integration implementation +- `references/4-conclude.md` - Review and fix any errors in the PostHog integration implementation +- `references/django.md` - Django - docs +- `references/identify-users.md` - Identify users - docs + +The example project shows the target implementation pattern. Consult the documentation for API details. + +## Key principles + +- **Environment variables**: Always use environment variables for PostHog keys. Never hardcode them. +- **Minimal changes**: Add PostHog code alongside existing integrations. Don't replace or restructure existing code. +- **Match the example**: Your implementation should follow the example project's patterns as closely as possible. + +## Framework guidelines + +- Add 'posthog.integrations.django.PosthogContextMiddleware' to MIDDLEWARE it auto-extracts tracing headers and captures exceptions +- Initialize PostHog in AppConfig.ready() with api_key and host from environment variables +- Use the context API pattern with new_context(), identify_context(user_id), then capture() +- For login/logout views, create a new context since user state changes during the request +- Do NOT create custom middleware, distinct_id helpers, or conditional checks - the SDK handles these +- Remember that source code is available in the venv/site-packages directory +- posthog is the Python SDK package name +- Install dependencies with `pip install posthog` or `pip install -r requirements.txt` and do NOT use unquoted version specifiers like `>=` directly in shell commands +- In CLIs and scripts: MUST call posthog.shutdown() before exit or all events are lost +- Always use the Posthog() class constructor (instance-based API) instead of module-level posthog.api_key config +- Always include enable_exception_autocapture=True in the Posthog() constructor to automatically track exceptions +- NEVER send PII in capture() event properties — no emails, full names, phone numbers, physical addresses, IP addresses, or user-generated content +- PII belongs in identify() person properties, NOT in capture() event properties. Safe event properties are metadata like message_length, form_type, boolean flags. +- Register posthog_client.shutdown with atexit.register() to ensure all events are flushed on exit +- The Python SDK has NO identify() method — use posthog_client.set(distinct_id=user_id, properties={...}) to set person properties, or use identify_context(user_id) within a context + +## Identifying users + +Identify users during login and signup events. Refer to the example code and documentation for the correct identify pattern for this framework. If both frontend and backend code exist, pass the client-side session and distinct ID using `X-POSTHOG-DISTINCT-ID` and `X-POSTHOG-SESSION-ID` headers to maintain correlation. + +## Error tracking + +Add PostHog error tracking to relevant files, particularly around critical user flows and API boundaries. diff --git a/apps/basic-integration/django/django3-saas/.claude/skills/integration-django/references/1-begin.md b/apps/basic-integration/django/django3-saas/.claude/skills/integration-django/references/1-begin.md new file mode 100644 index 000000000..55f0a8326 --- /dev/null +++ b/apps/basic-integration/django/django3-saas/.claude/skills/integration-django/references/1-begin.md @@ -0,0 +1,56 @@ +--- +title: PostHog Setup - Begin +description: Start the event tracking setup process by analyzing the project and creating an event tracking plan +--- + +We're making an event tracking plan for this project. + +This is the first of several phases — plan the events, implement them, revise and validate changes, then conclude by creating a dashboard and writing a setup report. + +## Task list + +As soon as you've read this description and have a rough sense of the work, make a single **call `TaskCreate` immediately** before reading any reference file or beginning analysis. The user is watching the task pane and shouldn't see it sit empty. + +It's fine if your first list is incomplete or imprecise. Seed it with whatever high-level items you can infer from the overview above, then call `TaskCreate` again (or `TaskUpdate` to refine existing items) every time your understanding sharpens: after a phase reveals work you didn't anticipate, after planning surfaces concrete sub-items, after you hit something new. Use `TaskUpdate` to mark items `in_progress` when you start them and `completed` when you finish. Keeping the list current matters more than getting it right on the first call. + +Keep task titles broad and job-oriented. Describe the purpose or area of work with wording like "Planning event tracking", "Identifying users", "Installing PostHog", "Capturing events", or "Creating dashboards", not the specific files, paths, or symbols involved. Adjust the task names according to the user's project and context. + +Before proceeding, find any existing `posthog.capture()` code. Make note of event name formatting. + +From the project's file list, select between 10 and 15 files that might have interesting business value for event tracking, especially conversion and churn events. Also look for additional files related to login that could be used for identifying users, along with error handling. Read the files. If a file is already well-covered by PostHog events, replace it with another option. Do not spawn subagents. + +Look for opportunities to track client-side events. + +**IMPORTANT: Server-side events are REQUIRED** if the project includes any instrumentable server-side code. If the project has API routes (e.g., `app/api/**/route.ts`) or Server Actions, you MUST include server-side events for critical business operations like: + + - Payment/checkout completion + - Webhook handlers + - Authentication endpoints + +Do not skip server-side events - they capture actions that cannot be tracked client-side. + +Create a new file with a JSON array at the root of the project: .posthog-events.json. It should include one object for each event we want to add with these exact field names: `event_name` (the event name), `event_description` (one sentence), and `file` (the file path the event goes in). The wizard reads this file to surface the plan in the UI. If events already exist, don't duplicate them; supplement them. + +Track actions only, not pageviews. These can be captured automatically. Exceptions can be made for "viewed"-type events that correspond to the top of a conversion funnel. + +As you review files, make an internal note of opportunities to identify users and catch errors. We'll need them for the next step. + +## Status + +Before beginning a phase of the setup, you will send a status message with the exact prefix '[STATUS]', as in: + +[STATUS] Checking project structure. + +Status to report in this phase: + +- Checking project structure +- Verifying PostHog dependencies +- Generating events based on project + +## Abort statuses + +If and only if the instructions have `[ABORT]` states specified, and you clearly match the conditions for an abort, emit the abort message. Do NOT attempt to exit or halt yourself — the wizard's middleware catches `[ABORT]` and terminates the run for you. + +--- + +**Upon completion, continue with:** [2-edit.md](2-edit.md) \ No newline at end of file diff --git a/apps/basic-integration/django/django3-saas/.claude/skills/integration-django/references/2-edit.md b/apps/basic-integration/django/django3-saas/.claude/skills/integration-django/references/2-edit.md new file mode 100644 index 000000000..e5f7ffd16 --- /dev/null +++ b/apps/basic-integration/django/django3-saas/.claude/skills/integration-django/references/2-edit.md @@ -0,0 +1,36 @@ +--- +title: PostHog Setup - Edit +description: Implement PostHog event tracking in the identified files, following best practices and the example project +--- + +For each of the files and events noted in .posthog-events.json, make edits to capture events using PostHog. Make sure to set up any helper files needed. Carefully examine the included example project code: your implementation should match it as closely as possible. Do not spawn subagents. + +Use environment variables for PostHog keys. Do not hardcode PostHog keys. + +If a file already has existing integration code for other tools or services, don't overwrite or remove that code. Place PostHog code below it. + +For each event, add useful properties, and use your access to the PostHog source code to ensure correctness. You also have access to documentation about creating new events with PostHog. Consider this documentation carefully and follow it closely before adding events. Your integration should be based on documented best practices. Carefully consider how the user project's framework version may impact the correct PostHog integration approach. + +Remember that you can find the source code for any dependency in the node_modules directory. This may be necessary to properly populate property names. There are also example project code files available via the PostHog MCP; use these for reference. + +Where possible, add calls for PostHog's identify() function on the client side upon events like logins and signups. Use the contents of login and signup forms to identify users on submit. If there is server-side code, pass the client-side session and distinct ID to the server-side code to identify the user. On the server side, make sure events have a matching distinct ID where relevant. + +It's essential to do this in both client code and server code, so that user behavior from both domains is easy to correlate. + +You should also add PostHog exception capture error tracking to these files where relevant. + +Remember: Do not alter the fundamental architecture of existing files. Make your additions minimal and targeted. + +Remember the documentation and example project resources you were provided at the beginning. Read them now. + +## Status + +Status to report in this phase: + +- Inserting PostHog capture code +- A status message for each file whose edits you are planning, including a high level summary of changes +- A status message for each file you have edited + +--- + +**Upon completion, continue with:** [3-revise.md](3-revise.md) \ No newline at end of file diff --git a/apps/basic-integration/django/django3-saas/.claude/skills/integration-django/references/3-revise.md b/apps/basic-integration/django/django3-saas/.claude/skills/integration-django/references/3-revise.md new file mode 100644 index 000000000..3b07f5069 --- /dev/null +++ b/apps/basic-integration/django/django3-saas/.claude/skills/integration-django/references/3-revise.md @@ -0,0 +1,22 @@ +--- +title: PostHog Setup - Revise +description: Review and fix any errors in the PostHog integration implementation +--- + +Check the project for errors. Read the package.json file for any type checking or build scripts that may provide input about what to fix. Remember that you can find the source code for any dependency in the node_modules directory. Do not spawn subagents. + +Ensure that any components created were actually used. + +Once all other tasks are complete, run any linter or prettier-like scripts found in the package.json, but ONLY on the files you have edited or created during this session. Do not run formatting or linting across the entire project's codebase. + +## Status + +Status to report in this phase: + +- Finding and correcting errors +- Report details of any errors you fix +- Linting, building and prettying + +--- + +**Upon completion, continue with:** [4-conclude.md](4-conclude.md) \ No newline at end of file diff --git a/apps/basic-integration/django/django3-saas/.claude/skills/integration-django/references/4-conclude.md b/apps/basic-integration/django/django3-saas/.claude/skills/integration-django/references/4-conclude.md new file mode 100644 index 000000000..d876d4353 --- /dev/null +++ b/apps/basic-integration/django/django3-saas/.claude/skills/integration-django/references/4-conclude.md @@ -0,0 +1,57 @@ +--- +title: PostHog Setup - Conclusion +description: Review and fix any errors in the PostHog integration implementation +--- + +Use the PostHog MCP to create a new dashboard named "Analytics basics (wizard)" based on the events created here. Keep the `(wizard)` tag with that exact casing so anyone browsing PostHog can see the wizard created this dashboard, and so a quick search for `(wizard)` surfaces every wizard-created artifact in one go. Make sure to use the exact same event names as implemented in the code. Populate it with up to five insights, with special emphasis on things like conversion funnels, churn events, and other business critical insights. + +Once the dashboard exists, emit its URL on its own line in your assistant message using this exact marker: `[DASHBOARD_URL] `. The wizard parses this marker from your visible message and surfaces the link in the success summary. Mentioning the URL only in thinking or in prose without the marker means the link is dropped. + +Search for a file called `.posthog-events.json` and read it for available events. + +Do not spawn subagents. + +Create the file posthog-setup-report.md. It should include a summary of the integration edits, a table with the event names, event descriptions, and files where events were added, a list of links for the dashboard and insights created, and a "Verify before merging" checklist (see below). Follow this format: + + +# PostHog post-wizard report + +The wizard has completed a deep integration of your project. [Detailed summary of changes] + +[table of events/descriptions/files] + +## Next steps + +We've built some insights and a dashboard for you to keep an eye on user behavior, based on the events we just instrumented: + +[links] + +## Verify before merging + +[checklist] + +### Agent skill + +We've left an agent skill folder in your project. You can use this context for further agent development when using Claude Code. This will help ensure the model provides the most up-to-date approaches for integrating PostHog. + + + +For the "Verify before merging" checklist, write GitHub-style checkboxes (`- [ ] ...`) covering what the developer (or their coding agent) still needs to do to take this from "wizard finished" to "merged". Include ONLY the items that actually apply to the integration you just performed — judge each against the code you changed in this run, and drop any that don't fit. Phrase each item as a concrete, checkable action. Candidate items, with the condition for including each: + +- Always: "Run a full production build (the wizard only verified the files it touched) and fix any lint or type errors introduced by the generated code." +- Always: "Run the test suite — call sites that were rewritten or instrumented may need updated mocks or fixtures." +- If you added environment variables: "Add the exact PostHog env var names you added to `.env.example` and any monorepo/bootstrap scripts so collaborators know what to set." +- If this integration ships a minified production browser bundle (most SPA/SSR web frameworks — e.g. Next.js, Nuxt, SvelteKit, Astro, Vite-based apps): "Wire source-map upload (`posthog-cli sourcemap` or your bundler's upload step) into CI so production stack traces de-minify." +- If LLM analytics was set up in this run: "Trigger the LLM call path(s) you instrumented and confirm `$ai_generation` events appear in PostHog AI Observability." +- If the app has user auth and an `identify` call was added: "Confirm the returning-visitor path also calls `identify` — a handler that only identifies on fresh login can leave returning sessions on anonymous distinct IDs." + +Do not invent items beyond what applies. If only the two "Always" items apply, the checklist is just those two. + +Upon completion, remove .posthog-events.json. + +## Status + +Status to report in this phase: + +- Configured dashboard: [insert PostHog dashboard URL] +- Created setup report: [insert full local file path] \ No newline at end of file diff --git a/apps/basic-integration/django/django3-saas/.claude/skills/integration-django/references/EXAMPLE.md b/apps/basic-integration/django/django3-saas/.claude/skills/integration-django/references/EXAMPLE.md new file mode 100644 index 000000000..b1def79a3 --- /dev/null +++ b/apps/basic-integration/django/django3-saas/.claude/skills/integration-django/references/EXAMPLE.md @@ -0,0 +1,1167 @@ +# PostHog Django Example Project + +Repository: https://github.com/PostHog/context-mill +Path: example-apps/django + +--- + +## README.md + +# PostHog Django example + +This is a [Django](https://djangoproject.com) example demonstrating PostHog integration with product analytics, error tracking, feature flags, and user identification. + +## Features + +- **Product analytics**: Track user events and behaviors +- **Error tracking**: Capture and track exceptions automatically +- **User identification**: Associate events with authenticated users via context +- **Feature flags**: Control feature rollouts with PostHog feature flags +- **Server-side tracking**: All tracking happens server-side with the Python SDK +- **Context middleware**: Automatic session and user context extraction + +## Getting started + +### 1. Install dependencies + +```bash +pip install posthog +``` + +### 2. Configure environment variables + +Create a `.env` file in the root directory: + +```bash +POSTHOG_PROJECT_TOKEN=your_posthog_project_token +POSTHOG_HOST=https://us.i.posthog.com +``` + +Get your PostHog project token from your [PostHog project settings](https://app.posthog.com/project/settings). + +### 3. Run migrations + +```bash +python manage.py migrate +``` + +### 4. Run the development server + +```bash +python manage.py runserver +``` + +Open [http://localhost:8000](http://localhost:8000) with your browser to see the app. + +## Project structure + +``` +django/ +├── manage.py # Django management script +├── requirements.txt # Python dependencies +├── .env.example # Environment variable template +├── .gitignore +├── posthog_example/ +│ ├── __init__.py +│ ├── settings.py # Django settings with PostHog config +│ ├── urls.py # URL routing +│ ├── wsgi.py # WSGI application +│ └── asgi.py # ASGI application +└── core/ + ├── __init__.py + ├── apps.py # AppConfig with PostHog initialization + ├── views.py # Views with event tracking examples + ├── urls.py # App URL patterns + └── templates/ + └── core/ + ├── base.html # Base template + ├── home.html # Home/login page + ├── burrito.html # Burrito page with event tracking + ├── dashboard.html # Dashboard with feature flag example + └── profile.html # Profile page +``` + +## Key integration points + +### PostHog initialization (core/apps.py) + +```python +import posthog +from django.conf import settings + +class CoreConfig(AppConfig): + name = 'core' + + def ready(self): + posthog.api_key = settings.POSTHOG_PROJECT_TOKEN + posthog.host = settings.POSTHOG_HOST +``` + +### Django settings configuration (settings.py) + +```python +import os + +# PostHog configuration +POSTHOG_PROJECT_TOKEN = os.environ.get('POSTHOG_PROJECT_TOKEN', '') +POSTHOG_HOST = os.environ.get('POSTHOG_HOST', 'https://us.i.posthog.com') + +MIDDLEWARE = [ + # ... other middleware + 'posthog.integrations.django.PosthogContextMiddleware', +] +``` + +### Built-in context middleware + +The PostHog SDK includes a Django middleware that automatically wraps all requests with a context. It extracts session and user information from request headers and tags all events captured during the request. + +The middleware automatically extracts: + +- **Session ID** from the `X-POSTHOG-SESSION-ID` header +- **Distinct ID** from the `X-POSTHOG-DISTINCT-ID` header +- **Current URL** as `$current_url` +- **Request method** as `$request_method` + +### User identification (core/views.py) + +```python +import posthog + +def login_view(request): + # ... authentication logic + if user: + with posthog.new_context(): + posthog.identify_context(str(user.id)) + posthog.tag('email', user.email) + posthog.tag('username', user.username) + posthog.capture('user_logged_in', properties={ + 'login_method': 'email', + }) +``` + +### Event tracking (core/views.py) + +```python +import posthog + +def consider_burrito(request): + user_id = str(request.user.id) if request.user.is_authenticated else 'anonymous' + + with posthog.new_context(): + posthog.identify_context(user_id) + posthog.capture('burrito_considered', properties={ + 'total_considerations': request.session.get('burrito_count', 0), + }) +``` + +### Feature flags (core/views.py) + +```python +import posthog + +def dashboard_view(request): + user_id = str(request.user.id) if request.user.is_authenticated else 'anonymous' + + show_new_feature = posthog.feature_enabled( + 'new-dashboard-feature', + distinct_id=user_id + ) + + return render(request, 'core/dashboard.html', { + 'show_new_feature': show_new_feature + }) +``` + +### Error tracking (core/views.py) + +Capture exceptions manually using `capture_exception()`: + +```python +import posthog + +def profile_view(request): + try: + risky_operation() + except Exception as e: + posthog.capture_exception(e) +``` + +## Frontend integration (optional) + +If you're using PostHog's JavaScript SDK on the frontend, enable tracing headers to connect frontend sessions with backend events: + +```javascript +posthog.init('', { + api_host: 'https://us.i.posthog.com', + __add_tracing_headers: ['your-backend-domain.com'], +}) +``` + +This automatically adds `X-POSTHOG-SESSION-ID` and `X-POSTHOG-DISTINCT-ID` headers to requests, which the Django middleware extracts to maintain context. + +## Learn more + +- [PostHog Django integration](https://posthog.com/docs/libraries/django) +- [PostHog Python SDK](https://posthog.com/docs/libraries/python) +- [PostHog documentation](https://posthog.com/docs) +- [Django documentation](https://docs.djangoproject.com/) + +--- + +## .env.example + +```example +POSTHOG_PROJECT_TOKEN= +POSTHOG_HOST=https://us.i.posthog.com +DJANGO_SECRET_KEY=your-secret-key-here +DEBUG=True + +``` + +--- + +## core/__init__.py + +```py +# Core app for PostHog Django example + +``` + +--- + +## core/apps.py + +```py +""" +Django AppConfig that initializes PostHog when the application starts. + +This ensures the SDK is configured once when Django starts, making it available throughout the application. +""" + +from django.apps import AppConfig +from django.conf import settings + + +class CoreConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'core' + + def ready(self): + """ + Initialize PostHog when Django starts. + + This method is called once when Django starts. We configure the + PostHog SDK here so it's available everywhere in the application. + + Note: Import posthog inside this method to avoid import issues + during Django's startup sequence. + """ + import posthog + + # Configure PostHog with settings from Django settings + posthog.api_key = settings.POSTHOG_PROJECT_TOKEN + posthog.host = settings.POSTHOG_HOST + + # Disable PostHog if configured (useful for testing) + if settings.POSTHOG_DISABLED: + posthog.disabled = True + + # Optional: Enable debug mode in development + if settings.DEBUG: + posthog.debug = True + +``` + +--- + +## core/templates/core/base.html + +```html + + + + + + {% block title %}PostHog Django example{% endblock %} + + + + {% if user.is_authenticated %} + + {% endif %} + +
+ {% if messages %} +
+ {% for message in messages %} +
{{ message }}
+ {% endfor %} +
+ {% endif %} + + {% block content %}{% endblock %} +
+ + {% block scripts %}{% endblock %} + + + +``` + +--- + +## core/templates/core/burrito.html + +```html +{% extends 'core/base.html' %} + +{% block title %}Burrito - PostHog Django example{% endblock %} + +{% block content %} +
+

Burrito consideration tracker

+

This page demonstrates custom event tracking with PostHog.

+
+ +
+

Times considered

+
{{ burrito_count }}
+ +
+ +
+

How event tracking works

+

Each time you click the button, a burrito_considered event is sent to PostHog:

+
from posthog import new_context, identify_context, capture
+
+with new_context():
+    identify_context(user_id)
+    capture('burrito_considered', properties={
+        'total_considerations': count,
+    })
+
+{% endblock %} + +{% block scripts %} + +{% endblock %} + +``` + +--- + +## core/templates/core/dashboard.html + +```html +{% extends 'core/base.html' %} + +{% block title %}Dashboard - PostHog Django example{% endblock %} + +{% block content %} +
+

Dashboard

+

Welcome back, {{ user.username }}!

+
+ +
+

Feature flags

+

Feature flags allow you to control feature rollouts and run A/B tests.

+ + {% if show_new_feature %} +
+

New feature enabled!

+

+ This section is only visible because the new-dashboard-feature + flag is enabled for your user. +

+ {% if feature_config %} +

Feature config: {{ feature_config }}

+ {% endif %} +
+ {% else %} +
+

+ The new-dashboard-feature flag is not enabled for your user. + Create this flag in your PostHog project to see it in action. +

+
+ {% endif %} +
+ +
+

How feature flags work

+
# Check if a feature flag is enabled
+show_feature = posthog.feature_enabled(
+    'new-dashboard-feature',
+    distinct_id=user_id,
+    person_properties={
+        'email': user.email,
+        'is_staff': user.is_staff,
+    }
+)
+
+# Get feature flag payload for configuration
+config = posthog.get_feature_flag_payload(
+    'new-dashboard-feature',
+    distinct_id=user_id,
+)
+
+{% endblock %} + +``` + +--- + +## core/templates/core/home.html + +```html +{% extends 'core/base.html' %} + +{% block title %}Login - PostHog Django example{% endblock %} + +{% block content %} +
+

PostHog Django example

+

Welcome! This example demonstrates PostHog integration with Django.

+
+ +
+

Login

+

Login to see PostHog analytics in action.

+ +
+ {% csrf_token %} + + + +
+ +

+ Tip: Create a user with python manage.py createsuperuser +

+
+ +
+

What this example demonstrates

+
    +
  • User identification - Users are identified with identify_context() on login
  • +
  • Pageview tracking - Middleware extracts session and user context
  • +
  • Event tracking - Custom events captured with capture() in context
  • +
  • Feature flags - Conditional features with posthog.feature_enabled()
  • +
  • Error tracking - Exceptions captured with capture_exception()
  • +
+
+{% endblock %} + +``` + +--- + +## core/templates/core/profile.html + +```html +{% extends 'core/base.html' %} + +{% block title %}Profile - PostHog Django example{% endblock %} + +{% block content %} +
+

Profile

+

This page demonstrates error tracking with PostHog.

+
+ +
+

User information

+ + + + + + + + + + + + + + + + + +
Username:{{ user.username }}
Email:{{ user.email|default:"Not set" }}
Date Joined:{{ user.date_joined }}
Staff Status:{{ user.is_staff|yesno:"Yes,No" }}
+
+ +
+

Error tracking demo

+

Click the buttons below to trigger different types of errors. These errors are caught and sent to PostHog.

+ +
+ + + +
+ + +
+ +
+

How error tracking works

+
import posthog
+
+try:
+    risky_operation()
+except Exception as e:
+    posthog.capture_exception(e)
+
+{% endblock %} + +{% block scripts %} + +{% endblock %} + +``` + +--- + +## core/urls.py + +```py +""" +URL configuration for the core app. + +This module defines all the URL patterns for the PostHog example views. +""" + +from django.urls import path +from . import views + +urlpatterns = [ + # Home login page + path('', views.home_view, name='home'), + + # Authentication + path('logout/', views.logout_view, name='logout'), + + # Dashboard with feature flags + path('dashboard/', views.dashboard_view, name='dashboard'), + + # Burrito example for event tracking + path('burrito/', views.burrito_view, name='burrito'), + path('api/burrito/consider/', views.consider_burrito_view, name='consider_burrito'), + + # Profile with error tracking + path('profile/', views.profile_view, name='profile'), + path('api/trigger-error/', views.trigger_error_view, name='trigger_error'), + + # Group analytics example + path('api/group-analytics/', views.group_analytics_view, name='group_analytics'), +] + +``` + +--- + +## core/views.py + +```py +"""Django views demonstrating PostHog integration patterns""" + +import posthog +from posthog import new_context, identify_context, tag, capture +from django.shortcuts import render, redirect +from django.contrib.auth import authenticate, login, logout +from django.contrib.auth.decorators import login_required +from django.contrib import messages +from django.http import JsonResponse +from django.views.decorators.http import require_POST + + +def home_view(request): + """Home page with login functionality""" + if request.user.is_authenticated: + return redirect('dashboard') + + if request.method == 'POST': + username = request.POST.get('username') + password = request.POST.get('password') + + user = authenticate(request, username=username, password=password) + + if user is not None: + login(request, user) + + # PostHog: Identify user and capture login event + with new_context(): + identify_context(str(user.id)) + + # Set person properties (PII goes in tag, not capture) + tag('email', user.email) + tag('username', user.username) + tag('name', user.get_full_name() or user.username) + tag('is_staff', user.is_staff) + tag('date_joined', user.date_joined.isoformat()) + + capture('user_logged_in', properties={ + 'login_method': 'email', + }) + + return redirect('dashboard') + else: + messages.error(request, 'Invalid username or password') + + return render(request, 'core/home.html') + + +def logout_view(request): + """Logout the current user""" + if request.user.is_authenticated: + user_id = str(request.user.id) + + # PostHog: Track logout before session ends + with new_context(): + identify_context(user_id) + capture('user_logged_out') + + logout(request) + + return redirect('home') + + +@login_required +def dashboard_view(request): + """Dashboard page with feature flag example""" + user_id = str(request.user.id) + + # PostHog: Track dashboard view + with new_context(): + identify_context(user_id) + capture('dashboard_viewed', properties={ + 'is_staff': request.user.is_staff, + }) + + # PostHog: Check feature flag + show_new_feature = posthog.feature_enabled( + 'new-dashboard-feature', + distinct_id=user_id, + person_properties={ + 'email': request.user.email, + 'is_staff': request.user.is_staff, + } + ) + + # PostHog: Get feature flag payload + feature_config = posthog.get_feature_flag_payload( + 'new-dashboard-feature', + distinct_id=user_id, + ) + + context = { + 'show_new_feature': show_new_feature, + 'feature_config': feature_config, + } + + return render(request, 'core/dashboard.html', context) + + +@login_required +def burrito_view(request): + """Example page demonstrating event tracking""" + count = request.session.get('burrito_count', 0) + + context = { + 'burrito_count': count, + } + + return render(request, 'core/burrito.html', context) + + +@login_required +@require_POST +def consider_burrito_view(request): + """API endpoint for tracking burrito considerations""" + count = request.session.get('burrito_count', 0) + 1 + request.session['burrito_count'] = count + + user_id = str(request.user.id) + + # PostHog: Track custom event + with new_context(): + identify_context(user_id) + capture('burrito_considered', properties={ + 'total_considerations': count, + }) + + return JsonResponse({ + 'success': True, + 'count': count, + }) + + +@login_required +def profile_view(request): + """Profile page with error tracking demonstration""" + user_id = str(request.user.id) + + # PostHog: Track profile view + with new_context(): + identify_context(user_id) + capture('profile_viewed') + + context = { + 'user': request.user, + } + + return render(request, 'core/profile.html', context) + + +@login_required +@require_POST +def trigger_error_view(request): + """API endpoint that demonstrates error tracking""" + try: + error_type = request.POST.get('error_type', 'generic') + + if error_type == 'value': + raise ValueError("Invalid value provided by user") + elif error_type == 'key': + data = {} + _ = data['nonexistent_key'] + else: + raise Exception("Something went wrong!") + + except Exception as e: + # PostHog: Capture exception + posthog.capture_exception(e) + + # PostHog: Track error trigger event + with new_context(): + identify_context(str(request.user.id)) + capture('error_triggered', properties={ + 'error_type': error_type, + 'error_message': str(e), + }) + + return JsonResponse({ + 'success': False, + 'error': str(e), + 'message': 'Error has been captured by PostHog', + }, status=400) + + return JsonResponse({'success': True}) + + +@login_required +def group_analytics_view(request): + """Example demonstrating group analytics""" + user_id = str(request.user.id) + + # PostHog: Identify group + posthog.group_identify( + group_type='company', + group_key='acme-corp', + properties={ + 'name': 'Acme Corporation', + 'plan': 'enterprise', + 'employee_count': 150, + } + ) + + # PostHog: Capture event with group + with new_context(): + identify_context(user_id) + capture( + 'feature_used', + properties={ + 'feature_name': 'group_analytics', + }, + groups={ + 'company': 'acme-corp', + } + ) + + return JsonResponse({ + 'success': True, + 'message': 'Group analytics event captured', + }) + +``` + +--- + +## manage.py + +```py +#!/usr/bin/env python +"""Django's command-line utility for administrative tasks.""" +import os +import sys + + +def main(): + """Run administrative tasks.""" + os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'posthog_example.settings') + try: + from django.core.management import execute_from_command_line + except ImportError as exc: + raise ImportError( + "Couldn't import Django. Are you sure it's installed and " + "available on your PYTHONPATH environment variable? Did you " + "forget to activate a virtual environment?" + ) from exc + execute_from_command_line(sys.argv) + + +if __name__ == '__main__': + main() + +``` + +--- + +## posthog_example/__init__.py + +```py +# PostHog Django example project + +``` + +--- + +## posthog_example/asgi.py + +```py +""" +ASGI config for PostHog example project +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'posthog_example.settings') + +application = get_asgi_application() + +``` + +--- + +## posthog_example/settings.py + +```py +"""Django settings for PostHog example project""" + +import os +from pathlib import Path + +try: + from dotenv import load_dotenv + load_dotenv() +except ImportError: + pass + +BASE_DIR = Path(__file__).resolve().parent.parent + +SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', 'django-insecure-example-key-change-in-production') + +DEBUG = os.environ.get('DEBUG', 'True').lower() == 'true' + +ALLOWED_HOSTS = ['localhost', '127.0.0.1'] + + +# PostHog configuration +POSTHOG_PROJECT_TOKEN = os.environ.get('POSTHOG_PROJECT_TOKEN', '') +POSTHOG_HOST = os.environ.get('POSTHOG_HOST', 'https://us.i.posthog.com') +POSTHOG_DISABLED = os.environ.get('POSTHOG_DISABLED', 'False').lower() == 'true' + + +INSTALLED_APPS = [ + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', + 'core.apps.CoreConfig', +] + +MIDDLEWARE = [ + 'django.middleware.security.SecurityMiddleware', + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.middleware.common.CommonMiddleware', + 'django.middleware.csrf.CsrfViewMiddleware', + 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'django.contrib.messages.middleware.MessageMiddleware', + 'django.middleware.clickjacking.XFrameOptionsMiddleware', + 'posthog.integrations.django.PosthogContextMiddleware', +] + +ROOT_URLCONF = 'posthog_example.urls' + +TEMPLATES = [ + { + 'BACKEND': 'django.template.backends.django.DjangoTemplates', + 'DIRS': [], + 'APP_DIRS': True, + 'OPTIONS': { + 'context_processors': [ + 'django.template.context_processors.debug', + 'django.template.context_processors.request', + 'django.contrib.auth.context_processors.auth', + 'django.contrib.messages.context_processors.messages', + ], + }, + }, +] + +WSGI_APPLICATION = 'posthog_example.wsgi.application' + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': BASE_DIR / 'db.sqlite3', + } +} + +AUTH_PASSWORD_VALIDATORS = [ + {'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'}, + {'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator'}, + {'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'}, + {'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'}, +] + +LANGUAGE_CODE = 'en-us' +TIME_ZONE = 'UTC' +USE_I18N = True +USE_TZ = True + +STATIC_URL = 'static/' + +DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' + +``` + +--- + +## posthog_example/urls.py + +```py +""" +URL configuration for PostHog example project +""" + +from django.contrib import admin +from django.urls import path, include + +urlpatterns = [ + path('admin/', admin.site.urls), + # Include the core app URLs for PostHog examples + path('', include('core.urls')), +] + +``` + +--- + +## posthog_example/wsgi.py + +```py +""" +WSGI config for PostHog example project +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'posthog_example.settings') + +application = get_wsgi_application() + +``` + +--- + +## requirements.txt + +```txt +Django>=4.2,<5.0 +posthog # Always use latest version +python-dotenv>=1.0.0 + +``` + +--- + diff --git a/apps/basic-integration/django/django3-saas/.claude/skills/integration-django/references/django.md b/apps/basic-integration/django/django3-saas/.claude/skills/integration-django/references/django.md new file mode 100644 index 000000000..5c8fff32c --- /dev/null +++ b/apps/basic-integration/django/django3-saas/.claude/skills/integration-django/references/django.md @@ -0,0 +1,249 @@ +# Django - Docs + +PostHog makes it easy to get data about traffic and usage of your Django app. Integrating PostHog enables analytics, custom events capture, feature flags, error tracking, and more. + +This guide walks you through integrating PostHog into your Django app using the [Python SDK](/docs/libraries/python.md). + +## Beta: integration via LLM + +Install PostHog for Django in seconds with our wizard by running this prompt with [LLM coding agents](/blog/envoy-wizard-llm-agent.md) like Cursor and Bolt, or by running it in your terminal. + +`npx @posthog/wizard` + +[Learn more](/wizard.md) + +Or, to integrate manually, continue with the rest of this guide. + +## Installation + +To start, run `pip install posthog` to install PostHog’s Python SDK. + +> **Note:** Version `7.x` of the PostHog Python SDK requires Python 3.10 or higher. + +Then, configure PostHog in your app config so it's initialized when Django starts: + +your\_app/apps.py + +PostHog AI + +```python +from django.apps import AppConfig +import posthog +class YourAppConfig(AppConfig): + name = 'your_app_name' + def ready(self): + posthog.api_key = '' + posthog.host = 'https://us.i.posthog.com' +``` + +Next, if you haven't done so already, add your `AppConfig` to `INSTALLED_APPS` in `settings.py`: + +settings.py + +PostHog AI + +```python +INSTALLED_APPS = [ + # ... other apps + 'your_app_name.apps.YourAppConfig', +] +``` + +You can find your project token and instance address in [your project settings](https://app.posthog.com/project/settings). + +To capture events from any file, import `posthog` and call the method you need. For example: + +Python + +PostHog AI + +```python +import posthog +from posthog import identify_context +def some_request(request): + with posthog.new_context(): + # Django includes request.user for anonymous visitors too. Only identify + # the context when the visitor is logged in. + if request.user.is_authenticated: + identify_context(str(request.user.pk)) + posthog.capture('event_name') +``` + +Events captured without a context or explicit `distinct_id` are sent as [anonymous events](/docs/data/anonymous-vs-identified-events.md) with an auto-generated `distinct_id`. See the [Python SDK docs](/docs/libraries/python.md#person-profiles-and-properties) for more details. + +## Identifying users + +> **Identifying users is required.** Backend events need a `distinct_id` that matches the ID your frontend uses when calling `posthog.identify()`. Without this, backend events are orphaned — they can't be linked to frontend event captures, [session replays](/docs/session-replay.md), [LLM traces](/docs/ai-engineering.md), or [error tracking](/docs/error-tracking.md). +> +> See our guide on [identifying users](/docs/getting-started/identify-users.md) for how to set this up. + +## Django contexts middleware + +The Python SDK provides a Django middleware that automatically wraps all requests with a [context](/docs/libraries/python.md#contexts). This middleware extracts session and user information from each request and tags all events captured during that request with relevant metadata. + +### Basic setup + +Add the middleware to your Django settings. If your app uses Django authentication, place it after `django.contrib.auth.middleware.AuthenticationMiddleware` so the middleware can use the authenticated Django user as a distinct ID fallback and capture the user's email. + +Python + +PostHog AI + +```python +MIDDLEWARE = [ + # ... other middleware + 'posthog.integrations.django.PosthogContextMiddleware', + # ... other middleware +] +``` + +The middleware uses the globally configured `posthog` client by default, so you don't need to create or pass it a separate client instance. + +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, falling back to the authenticated Django user's `pk` (Django's primary-key alias, which works with custom user models) +- **User email** from the authenticated Django user's `email` as `email` +- **Current URL** as `$current_url` +- **Request method** as `$request_method` +- **Request path** as `$request_path` +- **Forwarded IP address** from `X-Forwarded-For` as `$ip` +- **User agent** from `User-Agent` as `$user_agent` + +The session and distinct ID headers are sanitized before use. Empty values are ignored, control characters are removed, values are trimmed, and values are capped at 1000 characters. + +All events captured during the request (including exceptions) include these properties and are associated with the extracted session and distinct ID. + +If you're using [PostHog JS](/docs/libraries/js.md) on the frontend, configure [`tracing_headers`](/docs/libraries/js/config.md#tracing-headers) for your Django backend hostname so browser requests include the session and distinct ID headers. + +### Exception capture + +By default, the middleware captures exceptions and sends them to PostHog's error tracking using the globally configured `posthog` client. This includes Django view exceptions that Django converts into error responses. + +Disable this by setting: + +Python + +PostHog AI + +```python +# settings.py +POSTHOG_MW_CAPTURE_EXCEPTIONS = False +``` + +### Adding custom tags + +Use `POSTHOG_MW_EXTRA_TAGS` to add custom properties to all requests: + +Python + +PostHog AI + +```python +# settings.py +def add_user_tags(request): + # type: (HttpRequest) -> Dict[str, Any] + tags = {} + if hasattr(request, 'user') and request.user.is_authenticated: + # Use pk instead of id so this works with custom User primary keys. + tags['user_id'] = str(request.user.pk) + tags['email'] = request.user.email + return tags +POSTHOG_MW_EXTRA_TAGS = add_user_tags +``` + +#### Filtering requests + +Skip tracking for certain requests using `POSTHOG_MW_REQUEST_FILTER`: + +Python + +PostHog AI + +```python +# settings.py +def should_track_request(request): + # type: (HttpRequest) -> bool + # Don't track health checks or admin requests + if request.path.startswith('/health') or request.path.startswith('/admin'): + return False + return True +POSTHOG_MW_REQUEST_FILTER = should_track_request +``` + +### Modifying default tags + +Use `POSTHOG_MW_TAG_MAP` to modify or remove default tags: + +Python + +PostHog AI + +```python +# settings.py +def customize_tags(tags): + # type: (Dict[str, Any]) -> Dict[str, Any] + # Remove URL for privacy + tags.pop('$current_url', None) + # Add custom prefix to method + if '$request_method' in tags: + tags['http_method'] = tags.pop('$request_method') + return tags +POSTHOG_MW_TAG_MAP = customize_tags +``` + +### Complete configuration example + +Python + +PostHog AI + +```python +# settings.py +def add_request_context(request): + # type: (HttpRequest) -> Dict[str, Any] + tags = {} + if hasattr(request, 'user') and request.user.is_authenticated: + tags['user_type'] = 'authenticated' + # Use pk instead of id so this works with custom User primary keys. + tags['user_id'] = str(request.user.pk) + else: + tags['user_type'] = 'anonymous' + # Add request info + tags['user_agent'] = request.META.get('HTTP_USER_AGENT', '') + return tags +def filter_tracking(request): + # type: (HttpRequest) -> bool + # Skip internal endpoints + return not request.path.startswith(('/health', '/metrics', '/admin')) +def clean_tags(tags): + # type: (Dict[str, Any]) -> Dict[str, Any] + # Remove sensitive data + tags.pop('user_agent', None) + return tags +POSTHOG_MW_EXTRA_TAGS = add_request_context +POSTHOG_MW_REQUEST_FILTER = filter_tracking +POSTHOG_MW_TAG_MAP = clean_tags +POSTHOG_MW_CAPTURE_EXCEPTIONS = True +``` + +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 or Django authentication. + +The middleware supports both sync (WSGI) and async (ASGI) Django applications. In async mode, it uses Django's `request.auser()` API when available to avoid synchronous user access. + +## 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](/docs/libraries/python.md). + +Alternatively, the following tutorials can help you get started: + +- [Setting up Django analytics, feature flags, and more](/tutorials/django-analytics.md) +- [How to set up A/B tests in Django](/tutorials/django-ab-tests.md) + +### Community questions + +Ask a question + +### Was this page useful? + +HelpfulCould be better \ No newline at end of file diff --git a/apps/basic-integration/django/django3-saas/.claude/skills/integration-django/references/identify-users.md b/apps/basic-integration/django/django3-saas/.claude/skills/integration-django/references/identify-users.md new file mode 100644 index 000000000..1417e03a8 --- /dev/null +++ b/apps/basic-integration/django/django3-saas/.claude/skills/integration-django/references/identify-users.md @@ -0,0 +1,272 @@ +# Identify users - Docs + +Linking events to specific users enables you to build a full picture of how they're using your product across different sessions, devices, and platforms. + +This is straightforward to do when [capturing backend events](/docs/product-analytics/capture-events?tab=Node.js.md), as you associate events to a specific user using a `distinct_id`, which is a required argument. + +However, in the frontend of a [web](/docs/libraries/js/features.md#capturing-events) or [mobile app](/docs/libraries/ios.md#capturing-events), a `distinct_id` is not a required argument — PostHog's SDKs will generate an anonymous `distinct_id` for you automatically and you can capture events anonymously, provided you use the appropriate [configuration](/docs/libraries/js/features.md#capturing-anonymous-events). + +To link events to specific users, call `identify`: + +PostHog AI + +### Web + +```javascript +posthog.identify( + 'distinct_id', // Replace 'distinct_id' with your user's unique identifier + { email: 'max@hedgehogmail.com', name: 'Max Hedgehog' } // optional: set additional person properties +); +``` + +### Android + +```kotlin +PostHog.identify( + distinctId = distinctID, // Replace 'distinctID' with your user's unique identifier + // optional: set additional person properties + userProperties = mapOf( + "name" to "Max Hedgehog", + "email" to "max@hedgehogmail.com" + ) +) +``` + +### iOS + +```swift +PostHogSDK.shared.identify("distinct_id", // Replace "distinct_id" with your user's unique identifier + userProperties: ["name": "Max Hedgehog", "email": "max@hedgehogmail.com"]) // optional: set additional person properties +``` + +### React Native + +```jsx +posthog.identify('distinct_id', { // Replace "distinct_id" with your user's unique identifier + email: 'max@hedgehogmail.com', // optional: set additional person properties + name: 'Max Hedgehog' +}) +``` + +### Dart + +```dart +await Posthog().identify( + userId: 'distinct_id', // Replace "distinct_id" with your user's unique identifier + userProperties: { + 'email': 'max@hedgehogmail.com', // optional: set additional person properties + 'name': 'Max Hedgehog', + }, +); +``` + +Events captured after calling `identify` are identified events and this creates a person profile if one doesn't exist already. + +Due to the cost of processing them, anonymous events can be up to 4x cheaper than identified events, so it's recommended you only capture identified events when needed. + +## How identify works + +When a user starts browsing your website or app, PostHog automatically assigns them an **anonymous ID**, which is stored locally. + +Provided you've [configured persistence](/docs/libraries/js/persistence.md) to use cookies or `localStorage`, this enables us to track anonymous users – even across different sessions. + +By calling `identify` with a `distinct_id` of your choice (usually the user's ID in your database, or their email), you link the anonymous ID and distinct ID together. + +Thus, all past and future events made with that anonymous ID are now associated with the distinct ID. + +This enables you to do things like associate events with a user from before they log in for the first time, or associate their events across different devices or platforms. + +Using identify in the backend + +Although you can call `identify` using our backend SDKs, it is used most in frontends. This is because there is no concept of anonymous sessions in the backend SDKs, so calling `identify` only updates person profiles. + +## Best practices when using `identify` + +### 1\. Call `identify` as soon as you're able to + +In your frontend, you should call `identify` as soon as you're able to. + +Typically, this is every time your **app loads** for the first time, and directly after your **users log in**. + +This ensures that events sent during your users' sessions are correctly associated with them. + +You only need to call `identify` once per session, and you should avoid calling it multiple times unnecessarily. + +If you call `identify` multiple times with the same data without reloading the page in between, PostHog will ignore the subsequent calls. + +### 2\. Use unique strings for distinct IDs + +If two users have the same distinct ID, their data is merged and they are considered one user in PostHog. Two common ways this can happen are: + +- Your logic for generating IDs does not generate sufficiently strong IDs and you can end up with a clash where 2 users have the same ID. +- There's a bug, typo, or mistake in your code leading to most or all users being identified with generic IDs like `null`, `true`, or `distinctId`. + +PostHog also has built-in protections to stop the most common distinct ID mistakes. + +### 3\. Reset after logout + +If a user logs out on your frontend, you should call `reset()` to unlink any future events made on that device with that user. + +This is important if your users are sharing a computer, as otherwise all of those users are grouped together into a single user due to shared cookies between sessions. + +**We strongly recommend you call `reset` on logout even if you don't expect users to share a computer.** + +You can do that like so: + +PostHog AI + +### Web + +```javascript +posthog.reset() +``` + +### iOS + +```swift +PostHogSDK.shared.reset() +``` + +### Android + +```kotlin +PostHog.reset() +``` + +### React Native + +```jsx +posthog.reset() +``` + +### Dart + +```dart +await Posthog().reset(); +``` + +If you *also* want to reset the `device_id` so that the device will be considered a new device in future events, you can pass `true` as an argument: + +Web + +PostHog AI + +```javascript +posthog.reset(true) +``` + +### 4\. Person profiles and properties + +You'll notice that one of the parameters in the `identify` method is a `properties` object. + +This enables you to set [person properties](/docs/product-analytics/person-properties.md). + +Whenever possible, we recommend passing in all person properties you have available each time you call identify, as this ensures their person profile on PostHog is up to date. + +Person properties can also be set being adding a `$set` property to a event `capture` call. + +See our [person properties docs](/docs/product-analytics/person-properties.md) for more details on how to work with them and best practices. + +### 5\. Use deep links between platforms + +We recommend you call `identify` [as soon as you're able](#1-call-identify-as-soon-as-youre-able), typically when a user signs up or logs in. + +This doesn't work if one or both platforms are unauthenticated. Some examples of such cases are: + +- Onboarding and signup flows before authentication. +- Unauthenticated web pages redirecting to authenticated mobile apps. +- Authenticated web apps prompting an app download. + +In these cases, you can use a [deep link](https://developer.android.com/training/app-links/deep-linking) on Android and [universal links](https://developer.apple.com/documentation/xcode/supporting-universal-links-in-your-app) on iOS to identify users. + +1. Use `posthog.get_distinct_id()` to get the current distinct ID. Even if you cannot call identify because the user is unauthenticated, this will return an anonymous distinct ID generated by PostHog. +2. Add the distinct ID to the deep link as query parameters, along with other properties like UTM parameters. +3. When the user is redirected to the app, parse the deep link and handle the following cases: + +- The mobile app is already authenticated. In this case, call [`posthog.alias()`](/docs/libraries/js/features.md#alias) with the distinct ID from the web. This associates the two distinct IDs as a single person. +- The mobile app is unauthenticated. In this case, call [`posthog.identify()`](/docs/libraries/js/features.md#identifying-users) with the distinct ID from the web so pre-login mobile events stay connected to the web session. When the user later logs in on mobile, call `identify()` again with your canonical user ID. + +As long as you associate the distinct IDs with `posthog.identify()` or `posthog.alias()`, you can track events generated across platforms. + +Here's an example implementation for handling deep links from web to mobile: + +PostHog AI + +### iOS + +```swift +import PostHog +class DeepLinkIdentityManager { + static let shared = DeepLinkIdentityManager() + // MARK: - Deep Link Received + func handleDeepLink(_ url: URL, isAuthenticatedOnMobile: Bool) { + guard let webDistinctId = URLComponents(url: url, resolvingAgainstBaseURL: true)? + .queryItems?.first(where: { $0.name == "ph_distinct_id" })?.value else { + return + } + if isAuthenticatedOnMobile { + // The mobile app already knows the current user. + // Alias the incoming web distinct ID to that user. + PostHogSDK.shared.alias(webDistinctId) + } else { + // Reuse the web distinct ID until login on mobile. + PostHogSDK.shared.identify(webDistinctId) + } + } + // MARK: - Login/Signup + func handleLogin(canonicalUserId: String) { + // Switch from the web distinct ID (or a mobile anon ID) + // to your canonical user ID. + PostHogSDK.shared.identify(canonicalUserId) + // Set user properties, track signup event, etc. + } + func handleLogout() { + PostHogSDK.shared.reset() + } +} +``` + +### Android + +```kotlin +import android.net.Uri +import com.posthog.PostHog +object DeepLinkIdentityManager { + // Deep Link Received + fun handleDeepLink(uri: Uri, isAuthenticatedOnMobile: Boolean) { + val webDistinctId = uri.getQueryParameter("ph_distinct_id") ?: return + if (isAuthenticatedOnMobile) { + // The mobile app already knows the current user. + // Alias the incoming web distinct ID to that user. + PostHog.alias(webDistinctId) + } else { + // Reuse the web distinct ID until login on mobile. + PostHog.identify(webDistinctId) + } + } + // Login/Signup + fun handleLogin(canonicalUserId: String) { + // Switch from the web distinct ID (or a mobile anon ID) + // to your canonical user ID. + PostHog.identify(canonicalUserId) + // Set user properties, track signup event, etc. + } + fun handleLogout() { + PostHog.reset() + } +} +``` + +## Further reading + +- [Identifying users docs](/docs/product-analytics/identify.md) +- [How person processing works](/docs/how-posthog-works/ingestion-pipeline.md#2-person-processing) +- [An introductory guide to identifying users in PostHog](/tutorials/identifying-users-guide.md) + +### Community questions + +Ask a question + +### Was this page useful? + +HelpfulCould be better \ No newline at end of file diff --git a/apps/basic-integration/django/django3-saas/accounts/apps.py b/apps/basic-integration/django/django3-saas/accounts/apps.py new file mode 100644 index 000000000..0c1dd622c --- /dev/null +++ b/apps/basic-integration/django/django3-saas/accounts/apps.py @@ -0,0 +1,16 @@ +from django.apps import AppConfig +from django.conf import settings + + +class AccountsConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'accounts' + + def ready(self): + import posthog + + posthog.api_key = settings.POSTHOG_PROJECT_TOKEN + posthog.host = settings.POSTHOG_HOST + + if settings.DEBUG: + posthog.debug = True diff --git a/apps/basic-integration/django/django3-saas/accounts/views.py b/apps/basic-integration/django/django3-saas/accounts/views.py index 03b8ea066..2937f8790 100644 --- a/apps/basic-integration/django/django3-saas/accounts/views.py +++ b/apps/basic-integration/django/django3-saas/accounts/views.py @@ -1,3 +1,5 @@ +from posthog import new_context, identify_context, tag, capture + from django.shortcuts import render, redirect from django.contrib.auth import login from django.contrib.auth.decorators import login_required @@ -15,10 +17,30 @@ class CustomLoginView(LoginView): form_class = LoginForm template_name = 'accounts/login.html' + def form_valid(self, form): + response = super().form_valid(form) + user = self.request.user + with new_context(): + identify_context(str(user.pk)) + tag('username', user.username) + tag('is_staff', user.is_staff) + capture('user_logged_in', properties={ + 'login_method': 'email', + }) + return response + class CustomLogoutView(LogoutView): next_page = reverse_lazy('accounts:login') + def dispatch(self, request, *args, **kwargs): + if request.user.is_authenticated: + user_id = str(request.user.pk) + with new_context(): + identify_context(user_id) + capture('user_logged_out') + return super().dispatch(request, *args, **kwargs) + class CustomPasswordResetView(PasswordResetView): template_name = 'accounts/password_reset.html' @@ -49,6 +71,15 @@ def register(request): if form.is_valid(): user = form.save() login(request, user) + + with new_context(): + identify_context(str(user.pk)) + tag('username', user.username) + tag('is_staff', user.is_staff) + capture('user_registered', properties={ + 'has_company_name': bool(user.company_name), + }) + messages.success(request, 'Registration successful. Welcome!') return redirect('dashboard:index') else: @@ -63,6 +94,13 @@ def settings(request): form = ProfileForm(request.POST, instance=request.user) if form.is_valid(): form.save() + + with new_context(): + identify_context(str(request.user.pk)) + capture('profile_updated', properties={ + 'has_company_name': bool(request.user.company_name), + }) + messages.success(request, 'Settings updated.') return redirect('accounts:settings') else: diff --git a/apps/basic-integration/django/django3-saas/billing/views.py b/apps/basic-integration/django/django3-saas/billing/views.py index 075923e23..ed04780bd 100644 --- a/apps/basic-integration/django/django3-saas/billing/views.py +++ b/apps/basic-integration/django/django3-saas/billing/views.py @@ -1,3 +1,5 @@ +from posthog import new_context, identify_context, capture + import uuid from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.decorators import login_required @@ -21,6 +23,15 @@ def pricing(request): """Display pricing plans.""" plans = Plan.objects.filter(is_active=True) + + user_id = str(request.user.pk) if request.user.is_authenticated else None + with new_context(): + if user_id: + identify_context(user_id) + capture('pricing_viewed', properties={ + 'is_authenticated': request.user.is_authenticated, + }) + return render(request, 'billing/pricing.html', {'plans': plans}) @@ -70,6 +81,16 @@ def subscribe(request, plan_slug): current_period_end=now + timedelta(days=30 if plan.interval == 'month' else 365), stripe_subscription_id=f'sub_demo_{uuid.uuid4().hex[:12]}', ) + + with new_context(): + identify_context(str(request.user.pk)) + capture('subscription_started', properties={ + 'plan_name': plan.name, + 'plan_interval': plan.interval, + 'plan_price': float(plan.price), + 'is_demo': True, + }) + messages.success(request, f'Successfully subscribed to {plan.name}! (Demo mode)') return redirect('dashboard:index') @@ -116,6 +137,8 @@ def change_plan(request, plan_slug): return redirect('billing:subscribe', plan_slug=plan_slug) if request.method == 'POST': + old_plan_name = subscription.plan.name + if STRIPE_CONFIGURED and subscription.stripe_subscription_id and not subscription.stripe_subscription_id.startswith('sub_demo_'): # Update Stripe subscription try: @@ -130,6 +153,13 @@ def change_plan(request, plan_slug): ) subscription.plan = plan subscription.save() + with new_context(): + identify_context(str(request.user.pk)) + capture('subscription_changed', properties={ + 'old_plan_name': old_plan_name, + 'new_plan_name': plan.name, + 'new_plan_interval': plan.interval, + }) messages.success(request, f'Plan changed to {plan.name}.') except Exception as e: messages.error(request, f'Error changing plan: {str(e)}') @@ -137,6 +167,13 @@ def change_plan(request, plan_slug): # Demo mode subscription.plan = plan subscription.save() + with new_context(): + identify_context(str(request.user.pk)) + capture('subscription_changed', properties={ + 'old_plan_name': old_plan_name, + 'new_plan_name': plan.name, + 'new_plan_interval': plan.interval, + }) messages.success(request, f'Plan changed to {plan.name}. (Demo mode)') return redirect('billing:manage') @@ -168,9 +205,20 @@ def cancel(request): messages.error(request, f'Error canceling: {str(e)}') return redirect('billing:manage') + plan_name = subscription.plan.name + days_remaining = max(0, (subscription.current_period_end - timezone.now()).days) + subscription.status = 'canceled' subscription.canceled_at = timezone.now() subscription.save() + + with new_context(): + identify_context(str(request.user.pk)) + capture('subscription_canceled', properties={ + 'plan_name': plan_name, + 'days_remaining': days_remaining, + }) + messages.success(request, 'Subscription canceled. You will have access until the end of your billing period.') return redirect('billing:manage') @@ -270,6 +318,13 @@ def _handle_checkout_completed(session): stripe_customer_id=stripe_sub['customer'], ) + with new_context(): + identify_context(str(user.pk)) + capture('checkout_completed', properties={ + 'plan_name': plan.name, + 'plan_interval': plan.interval, + }) + def _handle_subscription_updated(subscription_data): """Update subscription status.""" @@ -323,5 +378,12 @@ def _handle_payment_failed(invoice): ) subscription.status = 'past_due' subscription.save() + + with new_context(): + identify_context(str(subscription.user.pk)) + capture('payment_failed', properties={ + 'plan_name': subscription.plan.name, + }) + except Subscription.DoesNotExist: pass diff --git a/apps/basic-integration/django/django3-saas/config/settings.py b/apps/basic-integration/django/django3-saas/config/settings.py index 3c02dea1b..7231e0d59 100644 --- a/apps/basic-integration/django/django3-saas/config/settings.py +++ b/apps/basic-integration/django/django3-saas/config/settings.py @@ -12,6 +12,10 @@ ALLOWED_HOSTS = [h.strip() for h in os.environ.get('ALLOWED_HOSTS', 'localhost,127.0.0.1').split(',')] +# PostHog configuration +POSTHOG_PROJECT_TOKEN = os.environ.get('POSTHOG_PROJECT_TOKEN', '') +POSTHOG_HOST = os.environ.get('POSTHOG_HOST', 'https://us.i.posthog.com') + INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', @@ -34,6 +38,7 @@ 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', + 'posthog.integrations.django.PosthogContextMiddleware', ] ROOT_URLCONF = 'config.urls' diff --git a/apps/basic-integration/django/django3-saas/dashboard/views.py b/apps/basic-integration/django/django3-saas/dashboard/views.py index be99138b9..c42d357cb 100644 --- a/apps/basic-integration/django/django3-saas/dashboard/views.py +++ b/apps/basic-integration/django/django3-saas/dashboard/views.py @@ -1,3 +1,5 @@ +from posthog import new_context, identify_context, capture + from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.decorators import login_required from django.contrib import messages @@ -60,6 +62,10 @@ def create_project(request): description=f'Created project: {project.name}' ) + with new_context(): + identify_context(str(request.user.pk)) + capture('project_created') + messages.success(request, 'Project created.') return redirect('dashboard:projects') else: @@ -83,6 +89,10 @@ def edit_project(request, pk): description=f'Updated project: {project.name}' ) + with new_context(): + identify_context(str(request.user.pk)) + capture('project_updated') + messages.success(request, 'Project updated.') return redirect('dashboard:projects') else: @@ -105,6 +115,10 @@ def delete_project(request, pk): description=f'Deleted project: {name}' ) + with new_context(): + identify_context(str(request.user.pk)) + capture('project_deleted') + messages.success(request, 'Project deleted.') return redirect('dashboard:projects') diff --git a/apps/basic-integration/django/django3-saas/posthog-setup-report.md b/apps/basic-integration/django/django3-saas/posthog-setup-report.md new file mode 100644 index 000000000..8c07f66ec --- /dev/null +++ b/apps/basic-integration/django/django3-saas/posthog-setup-report.md @@ -0,0 +1,44 @@ + +# PostHog post-wizard report + +The wizard has completed a deep integration of PostHog into this Django SaaS application. The Python SDK was installed and configured to initialize via `accounts/apps.py` using Django's `AppConfig.ready()` hook. The `PosthogContextMiddleware` was added to `MIDDLEWARE` in `config/settings.py` to automatically capture session/user context on every request. Event tracking was added across the three core apps — accounts, billing, and dashboard — covering the full user lifecycle from registration through subscription management and project activity. Users are identified via `identify_context()` on login and signup so backend events are linked to the correct person profile. + +| Event Name | Description | File | +|---|---|---| +| `user_registered` | A new user completes registration and their account is created. | `accounts/views.py` | +| `user_logged_in` | An existing user successfully authenticates and logs in. | `accounts/views.py` | +| `user_logged_out` | An authenticated user ends their session by logging out. | `accounts/views.py` | +| `profile_updated` | A user saves changes to their profile settings. | `accounts/views.py` | +| `pricing_viewed` | A visitor views the pricing page, the top of the subscription conversion funnel. | `billing/views.py` | +| `subscription_started` | A user successfully subscribes to a paid plan. | `billing/views.py` | +| `subscription_changed` | A subscriber switches from one plan to another. | `billing/views.py` | +| `subscription_canceled` | A subscriber cancels their active subscription. | `billing/views.py` | +| `checkout_completed` | A Stripe checkout session completes and a subscription is activated. | `billing/views.py` | +| `payment_failed` | A subscription payment attempt fails, putting the account into past-due status. | `billing/views.py` | +| `project_created` | A user successfully creates a new project in their dashboard. | `dashboard/views.py` | +| `project_updated` | A user saves edits to an existing project. | `dashboard/views.py` | +| `project_deleted` | A user permanently deletes one of their projects. | `dashboard/views.py` | + +## Next steps + +We've built some insights and a dashboard for you to keep an eye on user behavior, based on the events we just instrumented: + +- [Analytics basics (wizard) — Dashboard](https://us.posthog.com/project/483112/dashboard/1807626) +- [New User Registrations (wizard)](https://us.posthog.com/project/483112/insights/rh2pvKxH) +- [Pricing to Subscription Funnel (wizard)](https://us.posthog.com/project/483112/insights/embOSIsu) +- [New Subscriptions (wizard)](https://us.posthog.com/project/483112/insights/yQrN4S7a) +- [Subscription Cancellations (wizard)](https://us.posthog.com/project/483112/insights/KTVDdImf) +- [Project Activity (wizard)](https://us.posthog.com/project/483112/insights/HUUIQRsm) + +## Verify before merging + +- [ ] Run a full production build (the wizard only verified the files it touched) and fix any lint or type errors introduced by the generated code. +- [ ] Run the test suite — call sites that were rewritten or instrumented may need updated mocks or fixtures. +- [ ] Add `POSTHOG_PROJECT_TOKEN` and `POSTHOG_HOST` to `.env.example` and any bootstrap scripts so collaborators know what to set. +- [ ] Confirm the returning-visitor path also calls `identify` — a handler that only identifies on fresh login can leave returning sessions on anonymous distinct IDs. Consider identifying on each authenticated page load or relying on the `PosthogContextMiddleware` fallback (which uses Django's authenticated user pk automatically). + +### Agent skill + +We've left an agent skill folder in your project. You can use this context for further agent development when using Claude Code. This will help ensure the model provides the most up-to-date approaches for integrating PostHog. + + diff --git a/apps/basic-integration/django/django3-saas/requirements.txt b/apps/basic-integration/django/django3-saas/requirements.txt index e10e2f8dc..4cf0ee4c6 100644 --- a/apps/basic-integration/django/django3-saas/requirements.txt +++ b/apps/basic-integration/django/django3-saas/requirements.txt @@ -4,3 +4,4 @@ gunicorn>=21.0.0 whitenoise>=6.6.0 dj-database-url>=2.0.0 stripe>=7.0.0 +posthog