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/references/django.md b/apps/basic-integration/django/django3-saas/.claude/skills/integration-django/references/django.md new file mode 100644 index 000000000..e143a17f0 --- /dev/null +++ b/apps/basic-integration/django/django3-saas/.claude/skills/integration-django/references/django.md @@ -0,0 +1,300 @@ +> AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt + +# Django - Docs + +Copy page + +# 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. + +> These docs cover version `7.x` of the Python SDK, which requires Python 3.10 or higher. On Python 3.9? See [supported versions](#supported-versions). + +## Installation + +To start, run `pip install posthog` to install PostHog’s Python SDK. + +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` to associate events with the correct user. +> +> In Python, you can do this through a context. All event captures in the same context will be tagged automatically with the correct `distinct_id`. Typically, you would set a fresh context and identify at the top of each route. +> +> Python +> +> PostHog AI +> +> ```python +> from posthog import new_context, identify_context, capture +> @app.get("/foo") +> def foo(current_user: User = Depends(get_current_user)): +> with new_context(): # Set context at the top of a route +> identify_context(current_user.id) +> capture("foo_viewed") +> return {"status": "ok"} +> ``` +> +> When possible, write a small piece of **middleware** that resolves your authenticated user, wrap a context around the request, and identifies it. Every `capture()` downstream is then attributed *automatically*. The SDK's Django middleware does this automatically and you can replicate it when using the plain Python SDK. + +## 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. + +### Login and signup views + +The middleware reads `request.user` once, before your view runs. On a login or signup request the visitor is still anonymous at that point, so the request's context has no distinct ID. Calling `login()` inside the view doesn't change that. Everything captured during that request stays anonymous, including the login event itself. + +Identify the context from inside the request once you know who the user is. Django's auth signals are the natural place: + +Python + +PostHog AI + +```python +from django.contrib.auth.signals import user_logged_in +from django.dispatch import receiver +from posthog import identify_context +@receiver(user_logged_in) +def identify_posthog_user(sender, request, user, **kwargs): + identify_context(str(user.pk)) +``` + +Every capture later in that request is then attributed to the user who just logged in. Requests made after login don't need this. The middleware sees the authenticated user from the start. + +If you're using [PostHog JavaScript Web](/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) + +## Supported versions + +These docs cover version `7.x` of the PostHog Python SDK, which requires Python 3.10 or higher. Python 3.9 is no longer supported on `7.x.x` and higher — pin to the 6.x line with `pip install 'posthog<7'`, where `6.9.3` is the final release. + +Everything on this page works the same way on `6.9.3`. Event capture, the context API (`new_context`, `identify_context`, `set_context_session`), and `PosthogContextMiddleware` are identical on `6.9.3` and `7.0.0` — `7.0.0` only dropped Python 3.9 and bumped the optional LLM provider SDKs. That includes the middleware identifying the request context from the `X-POSTHOG-DISTINCT-ID` header and falling back to the authenticated user, which behaves the same across both lines. + +Later `7.x` releases add what the 6.x line does not receive, such as the Celery integration, tracing header sanitization, and `set_context_device_id`. They also changed the middleware's own captured properties: `7.x` sends the request IP as `$ip`, where `6.9.3` sends it as `$ip_address`, and `7.x` additionally captures `$request_path`, `$raw_user_agent`, and the authenticated user's `email`. + +### Still have questions? + +Ask PostHog AI + +### 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..8647dcb37 --- /dev/null +++ b/apps/basic-integration/django/django3-saas/.claude/skills/integration-django/references/identify-users.md @@ -0,0 +1,307 @@ +> AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt + +# Identify users - Docs + +Copy page + +# 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/usage.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/usage.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. + +#### Identify users when the web SDK loads + +If your app already knows the signed-in user when you initialize the JavaScript web SDK, the [`loaded` callback](/docs/libraries/js/config.md) is a convenient place to call `identify`. This identifies the user as soon as the SDK has loaded: + +Web + +PostHog AI + +```javascript +posthog.init('', { + api_host: 'https://us.i.posthog.com', + defaults: '2026-05-30', + loaded: (posthog) => { + if (currentUser?.id) { + posthog.identify(currentUser.id, { + email: currentUser.email, + name: currentUser.name, + }) + } + }, +}) +``` + +In this example, `currentUser` represents user data already available from your authentication system. If your app loads the user asynchronously, call `posthog.identify()` as soon as that data becomes available instead. + +### 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. + +**\`$set\` and \`$set\_once\` aren't stored on events** + +These properties only tell PostHog how to update person data during ingestion — they aren't kept on the stored event, so you can't filter, break down, or query events by them. To query the values you set, use [person properties](/docs/product-analytics/person-properties.md) instead. + +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/usage.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/usage.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) + +### Still have questions? + +Ask PostHog AI + +### Was this page useful? + +HelpfulCould be better \ No newline at end of file diff --git a/apps/basic-integration/django/django3-saas/.env.example b/apps/basic-integration/django/django3-saas/.env.example index b8e3ce5c6..d6d7519a3 100644 --- a/apps/basic-integration/django/django3-saas/.env.example +++ b/apps/basic-integration/django/django3-saas/.env.example @@ -3,6 +3,10 @@ SECRET_KEY=your-secret-key-here DEBUG=True ALLOWED_HOSTS=localhost,127.0.0.1 +# PostHog analytics +POSTHOG_PROJECT_TOKEN=your-posthog-project-token +POSTHOG_HOST=https://your-posthog-host + # Database (defaults to SQLite if not set) DATABASE_URL= 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..db55b9c53 --- /dev/null +++ b/apps/basic-integration/django/django3-saas/accounts/apps.py @@ -0,0 +1,60 @@ +import atexit + +from django.apps import AppConfig +from django.conf import settings + + +posthog_client = None + + +class AccountsConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'accounts' + + def ready(self): + global posthog_client + + missing_variables = [ + variable + for variable in ('POSTHOG_PROJECT_TOKEN', 'POSTHOG_HOST') + if not getattr(settings, variable) + ] + if missing_variables: + if settings.DEBUG: + variable = missing_variables[0] + raise RuntimeError( + f'{variable} variable required by PostHog is missing or un-configured, ' + f'this causes events to be silently missed. This error stops appearing ' + f'once {variable} is configured' + ) + return + + from posthog import Posthog + + posthog_client = Posthog( + project_api_key=settings.POSTHOG_PROJECT_TOKEN, + host=settings.POSTHOG_HOST, + enable_exception_autocapture=True, + ) + atexit.register(posthog_client.shutdown) + + from django.contrib.auth.signals import user_logged_in + from posthog import identify_context + + def identify_posthog_user(sender, request, user, **kwargs): + distinct_id = str(user.pk) + identify_context(distinct_id) + posthog_client.set( + distinct_id=distinct_id, + properties={ + 'email': user.email, + 'username': user.username, + 'name': user.get_full_name(), + }, + ) + + user_logged_in.connect( + identify_posthog_user, + dispatch_uid='accounts.identify_posthog_user', + weak=False, + ) diff --git a/apps/basic-integration/django/django3-saas/accounts/views.py b/apps/basic-integration/django/django3-saas/accounts/views.py index 03b8ea066..0a983956f 100644 --- a/apps/basic-integration/django/django3-saas/accounts/views.py +++ b/apps/basic-integration/django/django3-saas/accounts/views.py @@ -8,6 +8,7 @@ ) from django.contrib import messages from django.urls import reverse_lazy +from .apps import posthog_client from .forms import RegisterForm, LoginForm, ProfileForm @@ -15,10 +16,23 @@ class CustomLoginView(LoginView): form_class = LoginForm template_name = 'accounts/login.html' + def form_valid(self, form): + response = super().form_valid(form) + if posthog_client: + posthog_client.capture('user_logged_in', properties={ + 'login_method': 'password', + }) + return response + class CustomLogoutView(LogoutView): next_page = reverse_lazy('accounts:login') + def dispatch(self, request, *args, **kwargs): + if request.user.is_authenticated and posthog_client: + posthog_client.capture('user_logged_out') + return super().dispatch(request, *args, **kwargs) + class CustomPasswordResetView(PasswordResetView): template_name = 'accounts/password_reset.html' @@ -49,6 +63,10 @@ def register(request): if form.is_valid(): user = form.save() login(request, user) + if posthog_client: + posthog_client.capture('user_registered', properties={ + 'has_company_name': bool(user.company_name), + }) messages.success(request, 'Registration successful. Welcome!') return redirect('dashboard:index') else: @@ -63,6 +81,8 @@ def settings(request): form = ProfileForm(request.POST, instance=request.user) if form.is_valid(): form.save() + if posthog_client: + posthog_client.capture('account_settings_updated') 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..6abf392da 100644 --- a/apps/basic-integration/django/django3-saas/billing/views.py +++ b/apps/basic-integration/django/django3-saas/billing/views.py @@ -9,6 +9,7 @@ from django.utils import timezone from datetime import timedelta from .models import Plan, Subscription +from accounts.apps import posthog_client # Check if Stripe is configured STRIPE_CONFIGURED = bool(getattr(settings, 'STRIPE_SECRET_KEY', '')) @@ -36,6 +37,13 @@ def subscribe(request, plan_slug): return redirect('billing:manage') if request.method == 'POST': + checkout_provider = 'stripe' if STRIPE_CONFIGURED and plan.stripe_price_id else 'demo' + if posthog_client: + posthog_client.capture('checkout_started', properties={ + 'plan_slug': plan.slug, + 'billing_interval': plan.interval, + 'checkout_provider': checkout_provider, + }) if STRIPE_CONFIGURED and plan.stripe_price_id: # Create Stripe Checkout Session try: @@ -70,6 +78,12 @@ 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]}', ) + if posthog_client: + posthog_client.capture('subscription_activated', properties={ + 'plan_slug': plan.slug, + 'billing_interval': plan.interval, + 'activation_source': 'demo', + }) messages.success(request, f'Successfully subscribed to {plan.name}! (Demo mode)') return redirect('dashboard:index') @@ -130,6 +144,12 @@ def change_plan(request, plan_slug): ) subscription.plan = plan subscription.save() + if posthog_client: + posthog_client.capture('subscription_plan_changed', properties={ + 'plan_slug': plan.slug, + 'billing_interval': plan.interval, + 'change_source': 'stripe', + }) messages.success(request, f'Plan changed to {plan.name}.') except Exception as e: messages.error(request, f'Error changing plan: {str(e)}') @@ -137,6 +157,12 @@ def change_plan(request, plan_slug): # Demo mode subscription.plan = plan subscription.save() + if posthog_client: + posthog_client.capture('subscription_plan_changed', properties={ + 'plan_slug': plan.slug, + 'billing_interval': plan.interval, + 'change_source': 'demo', + }) messages.success(request, f'Plan changed to {plan.name}. (Demo mode)') return redirect('billing:manage') @@ -171,6 +197,11 @@ def cancel(request): subscription.status = 'canceled' subscription.canceled_at = timezone.now() subscription.save() + if posthog_client: + posthog_client.capture('subscription_canceled', properties={ + 'plan_slug': subscription.plan.slug, + 'cancellation_source': 'user', + }) messages.success(request, 'Subscription canceled. You will have access until the end of your billing period.') return redirect('billing:manage') @@ -269,6 +300,16 @@ def _handle_checkout_completed(session): stripe_subscription_id=stripe_sub['id'], stripe_customer_id=stripe_sub['customer'], ) + if posthog_client: + posthog_client.capture( + 'subscription_activated', + distinct_id=str(user.pk), + properties={ + 'plan_slug': plan.slug, + 'billing_interval': plan.interval, + 'activation_source': 'stripe_webhook', + }, + ) def _handle_subscription_updated(subscription_data): @@ -323,5 +364,13 @@ def _handle_payment_failed(invoice): ) subscription.status = 'past_due' subscription.save() + if posthog_client: + posthog_client.capture( + 'subscription_payment_failed', + distinct_id=str(subscription.user_id), + properties={ + 'plan_slug': subscription.plan.slug, + }, + ) 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..c1cf214f5 100644 --- a/apps/basic-integration/django/django3-saas/config/settings.py +++ b/apps/basic-integration/django/django3-saas/config/settings.py @@ -19,7 +19,7 @@ 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', - 'accounts', + 'accounts.apps.AccountsConfig', 'billing', 'dashboard', 'marketing', @@ -32,6 +32,7 @@ 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'posthog.integrations.django.PosthogContextMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] @@ -107,6 +108,10 @@ EMAIL_USE_TLS = os.environ.get('EMAIL_USE_TLS', 'False').lower() in ('true', '1', 'yes') DEFAULT_FROM_EMAIL = os.environ.get('DEFAULT_FROM_EMAIL', 'noreply@example.com') +# PostHog settings +POSTHOG_PROJECT_TOKEN = os.environ.get('POSTHOG_PROJECT_TOKEN') +POSTHOG_HOST = os.environ.get('POSTHOG_HOST') + # Stripe settings (optional - for billing integration) STRIPE_PUBLIC_KEY = os.environ.get('STRIPE_PUBLIC_KEY', '') STRIPE_SECRET_KEY = os.environ.get('STRIPE_SECRET_KEY', '') diff --git a/apps/basic-integration/django/django3-saas/dashboard/views.py b/apps/basic-integration/django/django3-saas/dashboard/views.py index be99138b9..7a2032dfb 100644 --- a/apps/basic-integration/django/django3-saas/dashboard/views.py +++ b/apps/basic-integration/django/django3-saas/dashboard/views.py @@ -5,6 +5,7 @@ from datetime import timedelta from .models import Project, ActivityLog from .forms import ProjectForm +from accounts.apps import posthog_client @login_required @@ -59,6 +60,10 @@ def create_project(request): action='project_created', description=f'Created project: {project.name}' ) + if posthog_client: + posthog_client.capture('project_created', properties={ + 'has_description': bool(project.description), + }) messages.success(request, 'Project created.') return redirect('dashboard:projects') @@ -82,6 +87,10 @@ def edit_project(request, pk): action='project_updated', description=f'Updated project: {project.name}' ) + if posthog_client: + posthog_client.capture('project_updated', properties={ + 'has_description': bool(project.description), + }) messages.success(request, 'Project updated.') return redirect('dashboard:projects') @@ -104,6 +113,8 @@ def delete_project(request, pk): action='project_deleted', description=f'Deleted project: {name}' ) + if posthog_client: + posthog_client.capture('project_deleted') messages.success(request, 'Project deleted.') return redirect('dashboard:projects') 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