From 365bb4ba1778cdc8dc4f159b1768622fd8974053 Mon Sep 17 00:00:00 2001 From: Jeremy Stretch Date: Tue, 30 Apr 2024 16:13:17 -0400 Subject: [PATCH] Fixes #15896: Retain proper formatting for JSON custom field default values --- netbox/extras/models/customfields.py | 3 ++- netbox/netbox/forms/base.py | 8 +++++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/netbox/extras/models/customfields.py b/netbox/extras/models/customfields.py index e78d1af23d3..c316a1c173f 100644 --- a/netbox/extras/models/customfields.py +++ b/netbox/extras/models/customfields.py @@ -1,4 +1,5 @@ import decimal +import json import re from datetime import datetime, date @@ -484,7 +485,7 @@ def to_form_field(self, set_initial=True, enforce_required=True, enforce_visibil # JSON elif self.type == CustomFieldTypeChoices.TYPE_JSON: - field = JSONField(required=required, initial=initial) + field = JSONField(required=required, initial=json.dumps(initial) if initial else '') # Object elif self.type == CustomFieldTypeChoices.TYPE_OBJECT: diff --git a/netbox/netbox/forms/base.py b/netbox/netbox/forms/base.py index 1a4155aaba8..84b6fbbca2a 100644 --- a/netbox/netbox/forms/base.py +++ b/netbox/netbox/forms/base.py @@ -1,3 +1,5 @@ +import json + from django import forms from django.contrib.contenttypes.models import ContentType from django.db.models import Q @@ -34,7 +36,11 @@ def _get_content_type(self): def _get_form_field(self, customfield): if self.instance.pk: form_field = customfield.to_form_field(set_initial=False) - form_field.initial = self.instance.custom_field_data.get(customfield.name, None) + initial = self.instance.custom_field_data.get(customfield.name) + if customfield.type == CustomFieldTypeChoices.TYPE_JSON: + form_field.initial = json.dumps(initial) + else: + form_field.initial = initial return form_field return customfield.to_form_field()