Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(devex): fix code that breaks on django 6 ahead of the bump (#123951)

Julian Bez9d45be9bb4a6
diff --git a/posthog/admin/admins/identity_provider_config_admin.py b/posthog/admin/admins/identity_provider_config_admin.py
index 443bc008482f..3bdc9b70d54a 100644
--- a/posthog/admin/admins/identity_provider_config_admin.py
+++ b/posthog/admin/admins/identity_provider_config_admin.py
@@ -1,6 +1,7 @@
from django.contrib import admin
from django.urls import reverse
from django.utils.html import format_html
+from django.utils.safestring import mark_safe
from posthog.models import IdentityProviderConfig
@@ -37,8 +38,8 @@ class IdentityProviderConfigAdmin(admin.ModelAdmin):
@admin.display(description="SAML Status")
def saml_status(self, obj):
if obj.has_saml:
- return format_html('<span style="color: green;">✓ Configured</span>')
- return format_html('<span style="color: gray;">Not Configured</span>')
+ return mark_safe('<span style="color: green;">✓ Configured</span>')
+ return mark_safe('<span style="color: gray;">Not Configured</span>')
@admin.display(description="Linked domains")
def linked_domains(self, obj):
diff --git a/posthog/admin/admins/organization_admin.py b/posthog/admin/admins/organization_admin.py
index d6b20a14580c..4c63758efe32 100644
--- a/posthog/admin/admins/organization_admin.py
+++ b/posthog/admin/admins/organization_admin.py
@@ -324,7 +324,7 @@ class OrganizationAdmin(admin.ModelAdmin):
def billing_link(self, organization: Organization) -> str:
url = f"{settings.BILLING_SERVICE_URL}/admin/billing/customer/?q={organization.pk}"
- return format_html(f'<a href="{url}">Billing →</a>')
+ return format_html('<a href="{}">Billing →</a>', url)
def usage_posthog(self, organization: Organization):
return format_html(
diff --git a/posthog/admin/admins/organization_domain_admin.py b/posthog/admin/admins/organization_domain_admin.py
index 0129598b7857..681de0865952 100644
--- a/posthog/admin/admins/organization_domain_admin.py
+++ b/posthog/admin/admins/organization_domain_admin.py
@@ -1,6 +1,7 @@
from django.contrib import admin
from django.urls import reverse
from django.utils.html import format_html
+from django.utils.safestring import mark_safe
from posthog.models import OrganizationDomain
@@ -59,5 +60,5 @@ class OrganizationDomainAdmin(admin.ModelAdmin):
def saml_status(self, obj):
"""Display SAML configuration status"""
if obj.saml_identity_provider_configs.exists():
- return format_html('<span style="color: green;">✓ Configured</span>')
- return format_html('<span style="color: gray;">Not Configured</span>')
+ return mark_safe('<span style="color: green;">✓ Configured</span>')
+ return mark_safe('<span style="color: gray;">Not Configured</span>')
diff --git a/posthog/admin/admins/team_admin.py b/posthog/admin/admins/team_admin.py
index 402bc27a4a8a..747726f94dba 100644
--- a/posthog/admin/admins/team_admin.py
+++ b/posthog/admin/admins/team_admin.py
@@ -403,7 +403,7 @@ class TeamAdmin(admin.ModelAdmin):
return "-"
client = get_personhog_client()
if client is None:
- return format_html("<em>personhog client not configured</em>")
+ return mark_safe("<em>personhog client not configured</em>")
try:
resp = client.get_group_type_mappings_by_team_id(GetGroupTypeMappingsByTeamIdRequest(team_id=team.id))
mappings_raw = sorted(
@@ -412,7 +412,7 @@ class TeamAdmin(admin.ModelAdmin):
)
except Exception as exc:
logger.warning("admin_group_type_mappings_fetch_failed", team_id=team.id, error=str(exc))
- return format_html(
+ return mark_safe(
'<p style="color: #856404; background: #fff3cd; border: 1px solid #ffc107; '
'padding: 8px 12px; border-radius: 4px; margin: 4px 0; font-size: 13px;">'
"Failed to fetch group type mappings from personhog</p>",
@@ -938,7 +938,7 @@ class TeamAdmin(admin.ModelAdmin):
state.suspended_at.isoformat(),
state.suspension_reason or "no reason recorded",
)
- return format_html("<em>Sending enabled</em>")
+ return mark_safe("<em>Sending enabled</em>")
@admin.display(description="Email sending actions")
def email_sending_suspension_actions(self, team: Team):
@@ -1260,7 +1260,7 @@ class TeamAdmin(admin.ModelAdmin):
'<span style="color:green"><strong>Enrolled</strong></span> since {}',
team.llm_gateway_enabled_at.isoformat(),
)
- return format_html("<em>Not enrolled</em>")
+ return mark_safe("<em>Not enrolled</em>")
@admin.display(description="Wallet (AI gateway credits)")
def ai_gateway_wallet(self, team: Team):
@@ -1292,7 +1292,7 @@ class TeamAdmin(admin.ModelAdmin):
.order_by("-created_at")[:20]
)
if not entries:
- return format_html("<em>(no top-ups recorded)</em>")
+ return mark_safe("<em>(no top-ups recorded)</em>")
rows = format_html_join(
"",
"<tr><td>{}</td><td>{}</td><td>${}</td><td>{}</td></tr>",
@@ -1343,9 +1343,9 @@ class TeamAdmin(admin.ModelAdmin):
except Exception as exc:
return format_html("<em>(cache read failed: {})</em>", str(exc))
if source == "absent":
- return format_html("<em>(no entry in Redis for this team; gateway denies until something writes one)</em>")
+ return mark_safe("<em>(no entry in Redis for this team; gateway denies until something writes one)</em>")
if source == "redis_negative":
- return format_html(
+ return mark_safe(
"<em>(negative-cache sentinel in Redis; gateway treats as default-deny "
"until the entry expires, default 24h)</em>"
)
diff --git a/posthog/admin/admins/user_admin.py b/posthog/admin/admins/user_admin.py
index eebcb3daa577..c55b02b61266 100644
--- a/posthog/admin/admins/user_admin.py
+++ b/posthog/admin/admins/user_admin.py
@@ -21,6 +21,7 @@ from django.template.response import TemplateResponse
from django.urls import reverse
from django.utils.html import format_html
from django.utils.http import urlencode
+from django.utils.safestring import mark_safe
from django.utils.translation import (
gettext,
gettext_lazy as _,
@@ -242,9 +243,9 @@ class UserAdmin(DjangoUserAdmin):
@admin.display(description="Email Verification")
def email_verification_status(self, user: User):
if user.is_email_verified:
- return format_html('<p style="color: green;">✓ Verified</p>')
+ return mark_safe('<p style="color: green;">✓ Verified</p>')
else:
- return format_html(
+ return mark_safe(
'<p style="color: red;">✗ Not verified</p><br>'
'<a href="#" class="button" id="send_verification_email_button">Send verification email</a>'
)
@@ -271,7 +272,7 @@ class UserAdmin(DjangoUserAdmin):
status_text,
)
else:
- return format_html('<p style="color: gray;">✗ Not configured</p>')
+ return mark_safe('<p style="color: gray;">✗ Not configured</p>')
def change_view(self, request, object_id, form_url="", extra_context=None):
"""Override change view to handle email verification button."""
diff --git a/products/ai_observability/backend/models/llm_prompt.py b/products/ai_observability/backend/models/llm_prompt.py
index 288c6007d256..15f2d76653f9 100644
--- a/products/ai_observability/backend/models/llm_prompt.py
+++ b/products/ai_observability/backend/models/llm_prompt.py
@@ -127,7 +127,7 @@ class LLMPromptDependency(UUIDModel):
class Meta:
constraints = [
models.CheckConstraint(
- check=models.Q(child_version__isnull=False, child_label__isnull=True)
+ condition=models.Q(child_version__isnull=False, child_label__isnull=True)
| models.Q(child_version__isnull=True, child_label__isnull=False),
name="llm_prompt_dependency_version_xor_label",
),
diff --git a/products/autoresearch/backend/models.py b/products/autoresearch/backend/models.py
index 877548fb1ee6..4653dd98075e 100644
--- a/products/autoresearch/backend/models.py
+++ b/products/autoresearch/backend/models.py
@@ -16,7 +16,7 @@ UNIT_INTERVAL_VALIDATORS = [MinValueValidator(0.0), MaxValueValidator(1.0)]
def unit_interval_constraint(field: str, name: str) -> models.CheckConstraint:
return models.CheckConstraint(
- check=models.Q(**{f"{field}__isnull": True}) | models.Q(**{f"{field}__gte": 0.0, f"{field}__lte": 1.0}),
+ condition=models.Q(**{f"{field}__isnull": True}) | models.Q(**{f"{field}__gte": 0.0, f"{field}__lte": 1.0}),
name=name,
)
@@ -38,7 +38,7 @@ def min_value_constraint(field: str, minimum: int, name: str, *, nullable: bool
at_least = models.Q(**{f"{field}__gte": minimum})
if nullable:
at_least = models.Q(**{f"{field}__isnull": True}) | at_least
- return models.CheckConstraint(check=at_least, name=name)
+ return models.CheckConstraint(condition=at_least, name=name)
class AutoresearchPipeline(TeamScopedRootMixin, UUIDModel):
@@ -324,7 +324,7 @@ class AutoresearchModel(PipelineScopedModel):
unit_interval_constraint("holdout_score", "autoresearch_model_holdout_score_in_unit_range"),
unit_interval_constraint("realized_score", "autoresearch_model_realized_score_in_unit_range"),
models.CheckConstraint(
- check=models.Q(trained_on_start__isnull=True)
+ condition=models.Q(trained_on_start__isnull=True)
| models.Q(trained_on_end__isnull=True)
| models.Q(trained_on_start__lte=models.F("trained_on_end")),
name="autoresearch_model_trained_on_range_ordered",
diff --git a/products/batch_exports/backend/models/batch_export.py b/products/batch_exports/backend/models/batch_export.py
index 32a93faeabfa..81b89b7a4b0e 100644
--- a/products/batch_exports/backend/models/batch_export.py
+++ b/products/batch_exports/backend/models/batch_export.py
@@ -178,7 +178,7 @@ class BatchExportRun(UUIDTModel):
db_table = "posthog_batchexportrun"
constraints = [
models.CheckConstraint(
- check=(
+ condition=(
Q(batch_export__isnull=False, batch_export_on_demand__isnull=True)
| Q(batch_export__isnull=True, batch_export_on_demand__isnull=False)
),
diff --git a/products/business_knowledge/backend/logic.py b/products/business_knowledge/backend/logic.py
index 80513181df15..771848c59674 100644
--- a/products/business_knowledge/backend/logic.py
+++ b/products/business_knowledge/backend/logic.py
@@ -598,7 +598,7 @@ def _library_ids_subquery() -> Subquery:
return Subquery(
KnowledgeLibrarySource.objects.filter(source_id=OuterRef("pk"))
.values("source_id")
- .annotate(_ids=ArrayAgg("library_id", ordering="library_id"))
+ .annotate(_ids=ArrayAgg("library_id", order_by="library_id"))
.values("_ids")[:1]
)
diff --git a/products/cohorts/backend/models/cohort.py b/products/cohorts/backend/models/cohort.py
index 00c32b8f6df1..8f7ffaa7a5d3 100644
--- a/products/cohorts/backend/models/cohort.py
+++ b/products/cohorts/backend/models/cohort.py
@@ -354,19 +354,14 @@ class Cohort(FileSystemSyncMixin, RootTeamMixin, models.Model):
`cohort_type` isn't derived here — it's computed by the API serializer
(`validate_filters_and_compute_realtime_support`) — so a direct `Cohort.objects.create(...)`
gets a fresh `condition_type` but a stale/absent `cohort_type`."""
- # update_fields can arrive positionally (4th positional, after force_insert/force_update/using)
- # or as a keyword. Intercept it so _maintain_filter_shape_hashes can extend the frozen set.
- update_fields = args[3] if len(args) > 3 else kwargs.get("update_fields")
+ # Intercept update_fields so _maintain_filter_shape_hashes can extend the frozen set.
+ update_fields = kwargs.get("update_fields")
if update_fields is None or "filters" in update_fields:
self.condition_type = Cohort.compute_condition_type(self.filters)
if update_fields is not None and "condition_type" not in update_fields:
update_fields = [*update_fields, "condition_type"]
- maintained_update_fields = self._maintain_filter_shape_hashes(update_fields)
- if len(args) > 3:
- args = (*args[:3], maintained_update_fields, *args[4:])
- else:
- kwargs["update_fields"] = maintained_update_fields
+ kwargs["update_fields"] = self._maintain_filter_shape_hashes(update_fields)
super().save(*args, **kwargs)
def _maintain_filter_shape_hashes(self, update_fields: Iterable[str] | None) -> set[str] | None:
diff --git a/products/cohorts/backend/models/test/test_behavioral_backfill_dependencies.py b/products/cohorts/backend/models/test/test_behavioral_backfill_dependencies.py
index acf377f93519..300a17712f65 100644
--- a/products/cohorts/backend/models/test/test_behavioral_backfill_dependencies.py
+++ b/products/cohorts/backend/models/test/test_behavioral_backfill_dependencies.py
@@ -3,7 +3,6 @@ from unittest import mock
from django.test import override_settings
from django.utils import timezone
-from django.utils.deprecation import RemovedInDjango60Warning
from parameterized import parameterized
@@ -139,20 +138,6 @@ class TestBehavioralBackfillDependencies(BaseTest):
self.assertIsNone(cohort.last_backfill_events_at)
self.assertIsNone(cohort.last_realtime_cohort_calculation_at)
- def test_positional_filter_update_persists_maintained_fields(self) -> None:
- cohort = self._cohort(7)
- old_hash = cohort.filters_shape_hash
- Cohort.objects.filter(id=cohort.id).update(last_backfill_events_at=timezone.now())
- cohort.refresh_from_db()
-
- cohort.filters = self._filters(30)
- with self.assertWarns(RemovedInDjango60Warning):
- cohort.save(False, False, None, ["filters"])
-
- cohort.refresh_from_db()
- self.assertNotEqual(cohort.filters_shape_hash, old_hash)
- self.assertIsNone(cohort.last_backfill_events_at)
-
def test_non_filter_partial_save_does_not_maintain_shape(self) -> None:
cohort = self._cohort(7)
old_hash = cohort.filters_shape_hash
diff --git a/products/conversations/backend/api/email_settings.py b/products/conversations/backend/api/email_settings.py
index 4f741146a006..c335034ef940 100644
--- a/products/conversations/backend/api/email_settings.py
+++ b/products/conversations/backend/api/email_settings.py
@@ -39,6 +39,7 @@ from products.conversations.backend.mailgun import (
add_domain as mailgun_add_domain,
delete_domain as mailgun_delete_domain,
get_domain as mailgun_get_domain,
+ mime_bytes_with_crlf,
send_mime,
verify_domain as mailgun_verify_domain,
)
@@ -842,7 +843,7 @@ class EmailSendTestView(APIView):
)
email_message.attach_alternative(html_body, "text/html")
- mime_bytes = email_message.message().as_bytes(linesep="\r\n")
+ mime_bytes = mime_bytes_with_crlf(email_message)
try:
send_mime(config.domain, mime_bytes, recipients=[user.email])
diff --git a/products/conversations/backend/api/tests/test_email_endpoints.py b/products/conversations/backend/api/tests/test_email_endpoints.py
index 49888f8c6aaf..e4fb2cdd6da2 100644
--- a/products/conversations/backend/api/tests/test_email_endpoints.py
+++ b/products/conversations/backend/api/tests/test_email_endpoints.py
@@ -2000,7 +2000,7 @@ class TestSendEmailReplyMultiConfig(BaseTest):
assert b"From: " in mime_bytes
assert b"[email protected]" in mime_bytes
- # Guard against someone dropping linesep="\r\n" from the as_bytes() call.
+ # Guard against someone dropping linesep="\r\n" from mime_bytes_with_crlf().
# RFC 5322 wants CRLF; Django's default is LF-only.
assert b"\r\n" in mime_bytes
diff --git a/products/conversations/backend/mailgun.py b/products/conversations/backend/mailgun.py
index b9bae5e49300..f9d80015ae6a 100644
--- a/products/conversations/backend/mailgun.py
+++ b/products/conversations/backend/mailgun.py
@@ -1,7 +1,11 @@
"""Mailgun integration helpers for conversations email channel."""
+from email.generator import BytesGenerator
+from io import BytesIO
from typing import Any, TypedDict
+from django.core.mail import EmailMessage
+
import requests
import structlog
@@ -210,6 +214,17 @@ def delete_domain(domain: str) -> None:
resp.raise_for_status()
+def mime_bytes_with_crlf(email_message: EmailMessage) -> bytes:
+ """Serialize a Django email to MIME bytes with the CRLF line endings RFC 5322 requires.
+
+ Django 6 returns a stdlib `EmailMessage` from `message()`, whose `as_bytes()` has no `linesep`
+ argument, so this calls `BytesGenerator` directly. That works for the older MIME classes too.
+ """
+ buffer = BytesIO()
+ BytesGenerator(buffer, mangle_from_=False).flatten(email_message.message(), linesep="\r\n")
+ return buffer.getvalue()
+
+
def send_mime(domain: str, mime_bytes: bytes, recipients: list[str]) -> str:
"""Send a pre-built MIME message through Mailgun's per-domain endpoint.
diff --git a/products/conversations/backend/tasks/email.py b/products/conversations/backend/tasks/email.py
index debaa32b435c..2b56e4f3134f 100644
--- a/products/conversations/backend/tasks/email.py
+++ b/products/conversations/backend/tasks/email.py
@@ -23,6 +23,7 @@ from products.conversations.backend.mailgun import (
MailgunNotConfigured,
MailgunPermanentError,
MailgunTransientError,
+ mime_bytes_with_crlf,
send_mime,
)
from products.conversations.backend.models import EmailMessageMapping, EmailOutboxMessage, Ticket
@@ -211,7 +212,7 @@ def _process_outbox_row(outbox: EmailOutboxMessage) -> None:
email_message.attach_alternative(html_body, "text/html")
recipients = [ticket.email_from, *cc]
- mime_bytes = email_message.message().as_bytes(linesep="\r\n")
+ mime_bytes = mime_bytes_with_crlf(email_message)
# Check again right before the send. The delete can commit after the check at the top,
# and a row lock held across the Mailgun call would block every write to the ticket.
diff --git a/products/data_catalog/backend/models/certification.py b/products/data_catalog/backend/models/certification.py
index e47533b0b3e8..3655b9ed6236 100644
--- a/products/data_catalog/backend/models/certification.py
+++ b/products/data_catalog/backend/models/certification.py
@@ -71,7 +71,7 @@ class TableCertification(CreatedMetaFields, UpdatedMetaFields, UUIDModel):
class Meta:
constraints = [
models.CheckConstraint(
- check=(
+ condition=(
models.Q(table__isnull=False, saved_query__isnull=True)
| models.Q(table__isnull=True, saved_query__isnull=False)
),
diff --git a/products/experiments/backend/admin/experiment_admin.py b/products/experiments/backend/admin/experiment_admin.py
index 42a0b3baf508..11ec2233f86e 100644
--- a/products/experiments/backend/admin/experiment_admin.py
+++ b/products/experiments/backend/admin/experiment_admin.py
@@ -8,6 +8,7 @@ from django.http import HttpRequest, HttpResponseRedirect
from django.shortcuts import redirect
from django.urls import path, reverse
from django.utils.html import format_html
+from django.utils.safestring import mark_safe
from posthog.models.organization import Organization
@@ -226,7 +227,7 @@ class ExperimentAdmin(admin.ModelAdmin):
def engine(self, experiment: Experiment):
all_metrics = (experiment.metrics or []) + (experiment.metrics_secondary or [])
if has_legacy_metric(all_metrics):
- return format_html('<span style="color: orange;">Legacy</span>')
+ return mark_safe('<span style="color: orange;">Legacy</span>')
return ""
@admin.display(description="")
diff --git a/products/experiments/backend/admin/experiment_saved_metric_admin.py b/products/experiments/backend/admin/experiment_saved_metric_admin.py
index b92fbe0f3db6..1616335bb5ff 100644
--- a/products/experiments/backend/admin/experiment_saved_metric_admin.py
+++ b/products/experiments/backend/admin/experiment_saved_metric_admin.py
@@ -2,6 +2,7 @@ from django.contrib import admin, messages
from django.shortcuts import redirect
from django.urls import path, reverse
from django.utils.html import format_html
+from django.utils.safestring import mark_safe
from products.experiments.backend.legacy_migration import migrate_saved_metric
from products.experiments.backend.models.experiment import ExperimentSavedMetric
@@ -36,7 +37,7 @@ class ExperimentSavedMetricAdmin(admin.ModelAdmin):
def engine(self, saved_metric: ExperimentSavedMetric):
kind = saved_metric.query.get("kind") if saved_metric.query else None
if kind in ("ExperimentFunnelsQuery", "ExperimentTrendsQuery"):
- return format_html('<span style="color: orange;">Legacy</span>')
+ return mark_safe('<span style="color: orange;">Legacy</span>')
return ""
@admin.display(description="")
diff --git a/products/mcp_store/backend/models.py b/products/mcp_store/backend/models.py
index f7093d52e608..9a911c4ff364 100644
--- a/products/mcp_store/backend/models.py
+++ b/products/mcp_store/backend/models.py
@@ -532,7 +532,7 @@ class MCPToolPolicy(TeamScopedRootMixin, UUIDModel):
name="uniq_agent_tool_policy",
),
models.CheckConstraint(
- check=(
+ condition=(
Q(scope_type="team", scope_user__isnull=True, scope_service_account__isnull=True)
| Q(scope_type="member", scope_user__isnull=False, scope_service_account__isnull=True)
| Q(scope_type="agent", scope_user__isnull=True, scope_service_account__isnull=False)