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(dashboards): handle button tiles when creating from template (#69277)

Matt Pua1c1cd90031dc
diff --git a/frontend/src/scenes/dashboard/dashboardUtils.test.ts b/frontend/src/scenes/dashboard/dashboardUtils.test.ts
index 4b71287bcf27..9e8b499ccf7b 100644
--- a/frontend/src/scenes/dashboard/dashboardUtils.test.ts
+++ b/frontend/src/scenes/dashboard/dashboardUtils.test.ts
@@ -1,8 +1,9 @@
import { dayjs } from 'lib/dayjs'
-import { DashboardPlacement, DashboardTile, QueryBasedInsightModel } from '~/types'
+import { DashboardPlacement, DashboardTile, DashboardType, InsightModel, QueryBasedInsightModel } from '~/types'
import {
+ dashboardToSaveableTemplate,
getDashboardTileDisplayName,
isWidgetTileVisibleOnPlacement,
parseURLFilters,
@@ -36,6 +37,37 @@ describe('getDashboardTileDisplayName', () => {
})
})
+describe('dashboardToSaveableTemplate', () => {
+ it('serializes a button tile with a BUTTON type discriminator', () => {
+ const dashboard = {
+ name: 'My dashboard',
+ description: '',
+ filters: {},
+ tags: [],
+ tiles: [
+ {
+ id: 1,
+ button_tile: {
+ id: '1',
+ url: '/replay/home',
+ text: 'Watch replays',
+ placement: 'left',
+ style: 'primary',
+ },
+ layouts: {},
+ color: null,
+ },
+ ],
+ } as unknown as DashboardType<InsightModel>
+
+ const tile = dashboardToSaveableTemplate(dashboard)?.tiles[0]
+ expect(tile).toMatchObject({
+ type: 'BUTTON',
+ button_tile: { url: '/replay/home', text: 'Watch replays' },
+ })
+ })
+})
+
describe('isWidgetTileVisibleOnPlacement', () => {
it.each([
[DashboardPlacement.Dashboard, true],
diff --git a/frontend/src/scenes/dashboard/dashboardUtils.ts b/frontend/src/scenes/dashboard/dashboardUtils.ts
index 3fd010f66b62..e0c7b774275e 100644
--- a/frontend/src/scenes/dashboard/dashboardUtils.ts
+++ b/frontend/src/scenes/dashboard/dashboardUtils.ts
@@ -66,6 +66,7 @@ export function dashboardToSaveableTemplate(
}
if (tile.button_tile) {
return {
+ type: 'BUTTON' as const,
button_tile: {
url: tile.button_tile.url,
text: tile.button_tile.text,
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 5489665c4fba..ad7c12898c47 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -2649,6 +2649,7 @@ export type DashboardTemplateStoredTextTile = {
}
export type DashboardTemplateStoredButtonTile = {
+ type: 'BUTTON'
button_tile: {
url: string
text: string
diff --git a/posthog/api/test/dashboards/test_dashboard.py b/posthog/api/test/dashboards/test_dashboard.py
index 31341ab5dfa4..ab7b98fdbf22 100644
--- a/posthog/api/test/dashboards/test_dashboard.py
+++ b/posthog/api/test/dashboards/test_dashboard.py
@@ -2691,6 +2691,29 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):
},
]
+ @parameterized.expand(
+ [
+ ("inline_fields", {"type": "BUTTON", "url": "/replay/home", "text": "Watch replays", "layouts": {}}),
+ (
+ "nested_button_tile",
+ {"type": "BUTTON", "button_tile": {"url": "/replay/home", "text": "Watch replays"}, "layouts": {}},
+ ),
+ ]
+ )
+ def test_create_from_template_json_can_provide_button_tile(self, _name: str, button_tile: dict) -> None:
+ template: dict = {**valid_template, "tiles": [button_tile]}
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/dashboards/create_from_template_json",
+ {"template": template},
+ )
+ assert response.status_code == 200, response.json()
+
+ tiles = response.json()["tiles"]
+ assert len(tiles) == 1
+ assert tiles[0]["button_tile"]["url"] == "/replay/home"
+ assert tiles[0]["button_tile"]["text"] == "Watch replays"
+
def test_create_from_template_json_can_provide_query_tile(self) -> None:
template: dict = {
**valid_template,
diff --git a/posthog/helpers/dashboard_templates.py b/posthog/helpers/dashboard_templates.py
index 95b64a4e5994..2ab651a4f079 100644
--- a/posthog/helpers/dashboard_templates.py
+++ b/posthog/helpers/dashboard_templates.py
@@ -502,6 +502,7 @@ def create_from_template(
dashboard.name = template.template_name
dashboard.filters = template.dashboard_filters
dashboard.description = template.dashboard_description or ""
+
for template_tag in template.tags or []:
tag, _ = Tag.objects.get_or_create(
name=template_tag,
@@ -512,7 +513,8 @@ def create_from_template(
dashboard.save()
for template_tile in template.tiles or []:
- if template_tile["type"] == "INSIGHT":
+ tile_type = template_tile.get("type")
+ if tile_type == "INSIGHT":
query = template_tile.get("query", None)
_create_tile_for_insight(
dashboard,
@@ -523,7 +525,7 @@ def create_from_template(
layouts=template_tile.get("layouts"),
user=user,
)
- elif template_tile["type"] == "TEXT":
+ elif tile_type == "TEXT":
_create_tile_for_text(
dashboard,
color=template_tile.get("color"),
@@ -531,18 +533,19 @@ def create_from_template(
body=template_tile.get("body"),
transparent_background=template_tile.get("transparent_background"),
)
- elif template_tile["type"] == "BUTTON":
+ elif tile_type == "BUTTON":
+ button = {**template_tile, **(template_tile.get("button_tile") or {})}
_create_tile_for_button(
dashboard,
color=template_tile.get("color"),
layouts=template_tile.get("layouts"),
- url=template_tile.get("url", ""),
- text=template_tile.get("text", ""),
- placement=template_tile.get("placement", "left"),
- style=template_tile.get("style", "primary"),
+ url=button.get("url", ""),
+ text=button.get("text", ""),
+ placement=button.get("placement", "left"),
+ style=button.get("style", "primary"),
transparent_background=template_tile.get("transparent_background"),
)
- elif template_tile["type"] == "WIDGET":
+ elif tile_type == "WIDGET":
_create_tile_for_widget(
dashboard,
widget_type=template_tile.get("widget_type", ""),
diff --git a/products/dashboards/backend/migrations/0014_backfill_dashboardtemplate_button_tile_type.py b/products/dashboards/backend/migrations/0014_backfill_dashboardtemplate_button_tile_type.py
new file mode 100644
index 000000000000..946e0f8b7beb
--- /dev/null
+++ b/products/dashboards/backend/migrations/0014_backfill_dashboardtemplate_button_tile_type.py
@@ -0,0 +1,55 @@
+from django.core.paginator import Paginator
+from django.db import migrations
+
+import structlog
+
+
+def backfill_button_tile_type(apps, _) -> None:
+ """
+ Older save-as-template rows stored a button tile as `{"button_tile": {...}}` with no
+ top-level `type`, unlike text/insight/widget tiles which always had one. The template
+ reader (`create_from_template`) used to hard-index `template_tile["type"]`, so instantiating
+ one of these templates raised `KeyError: 'type'` and left a half-created dashboard behind.
+ The reader and the frontend serializer are now both fixed, but rows saved before that fix
+ still have the old shape sitting in the DB - this walks every DashboardTemplate and adds the
+ missing `"type": "BUTTON"` in place, so those templates instantiate cleanly too.
+ """
+ logger = structlog.get_logger(__name__)
+ DashboardTemplate = apps.get_model("dashboards", "DashboardTemplate")
+
+ templates = DashboardTemplate.objects.order_by("id").all()
+ paginator = Paginator(templates, 500) # process in pages so a huge tiles list doesn't sit in memory all at once
+ updated_count = 0
+
+ for page_number in paginator.page_range:
+ updated_templates = []
+
+ for template in paginator.page(page_number).object_list:
+ if not template.tiles:
+ continue
+
+ changed = False
+ for tile in template.tiles:
+ if isinstance(tile, dict) and tile.get("button_tile") is not None and "type" not in tile:
+ tile["type"] = "BUTTON"
+ changed = True
+
+ if changed:
+ updated_templates.append(template)
+
+ # One bulk_update per page: touches only the templates that actually needed a fix.
+ if updated_templates:
+ DashboardTemplate.objects.bulk_update(updated_templates, ["tiles"])
+ updated_count += len(updated_templates)
+
+ logger.info("backfill_dashboardtemplate_button_tile_type_done", updated_count=updated_count)
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("dashboards", "0013_dashboardtile_button_tile_id_idx"),
+ ]
+
+ operations = [
+ migrations.RunPython(backfill_button_tile_type, reverse_code=migrations.RunPython.noop),
+ ]
diff --git a/products/dashboards/backend/migrations/max_migration.txt b/products/dashboards/backend/migrations/max_migration.txt
index 7be944e51545..413795cece92 100644
--- a/products/dashboards/backend/migrations/max_migration.txt
+++ b/products/dashboards/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0013_dashboardtile_button_tile_id_idx
+0014_backfill_dashboardtemplate_button_tile_type