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.

fix(legal_documents): use autocomplete widget for organization FK to prevent timeout (#61765)

Rafael Audibert3aced845453f
diff --git a/products/legal_documents/backend/admin.py b/products/legal_documents/backend/admin.py
index a48dda5c1d92..331b43c456c6 100644
--- a/products/legal_documents/backend/admin.py
+++ b/products/legal_documents/backend/admin.py
@@ -67,6 +67,10 @@ class LegalDocumentAdminForm(forms.ModelForm):
@admin.register(LegalDocument)
class LegalDocumentAdmin(admin.ModelAdmin):
+ # FK to posthog.Organization — without this the add view renders a <select>
+ # of every org on Cloud, which times out. Autocomplete searches lazily via
+ # OrganizationAdmin.search_fields.
+ autocomplete_fields = ("organization",)
list_display = (
"id",
"document_type",
diff --git a/products/legal_documents/backend/tests/test_admin.py b/products/legal_documents/backend/tests/test_admin.py
index a61c6b1d1e04..aba345efdc3e 100644
--- a/products/legal_documents/backend/tests/test_admin.py
+++ b/products/legal_documents/backend/tests/test_admin.py
@@ -4,6 +4,7 @@ from posthog.test.base import APIBaseTest
from unittest.mock import patch
from django.contrib.admin import AdminSite
+from django.contrib.admin.widgets import AutocompleteSelect
from django.core.exceptions import ValidationError
from django.core.files.uploadedfile import SimpleUploadedFile, UploadedFile
from django.test import RequestFactory
@@ -184,6 +185,16 @@ class TestLegalDocumentAdminSave(APIBaseTest):
mock_storage.delete.assert_called_once_with(expected_key)
self.assertFalse(LegalDocument.objects.filter(id=document_id).exists())
+ def test_add_form_uses_autocomplete_for_organization(self) -> None:
+ # The organization FK must render an autocomplete widget, not the default
+ # <select> — the latter loads every org row into the page and times out
+ # the add view on Cloud.
+ add_form_class = self.admin.get_form(self._request(), obj=None, change=False)
+ widget = add_form_class.base_fields["organization"].widget
+ # Admin wraps FK widgets in RelatedFieldWidgetWrapper (the +add/edit links).
+ inner = getattr(widget, "widget", widget)
+ self.assertIsInstance(inner, AutocompleteSelect)
+
def test_change_view_form_saves_without_signed_pdf(self) -> None:
# The add form (LegalDocumentAdminForm) declares signed_pdf
# as a required FileField. If it leaks into the change view's form,