From dd707c97af7df048db7bb659fa11bc8002115804 Mon Sep 17 00:00:00 2001 From: Jeremy Stretch Date: Mon, 17 Aug 2020 11:08:14 -0400 Subject: [PATCH] Cache custom fields on instance prior to save() --- netbox/extras/forms.py | 15 +++++++++++++-- netbox/extras/models/customfields.py | 1 - netbox/extras/signals.py | 4 ---- 3 files changed, 13 insertions(+), 7 deletions(-) diff --git a/netbox/extras/forms.py b/netbox/extras/forms.py index cecbfae72..90ec828c7 100644 --- a/netbox/extras/forms.py +++ b/netbox/extras/forms.py @@ -29,6 +29,9 @@ class CustomFieldModelForm(forms.ModelForm): super().__init__(*args, **kwargs) + if self.instance._cf is None: + self.instance._cf = {} + self._append_customfield_fields() def _append_customfield_fields(self): @@ -48,9 +51,12 @@ class CustomFieldModelForm(forms.ModelForm): field_name = 'cf_{}'.format(cf.name) if self.instance.pk: self.fields[field_name] = cf.to_form_field(set_initial=False) - self.fields[field_name].initial = self.custom_field_values.get(cf.name) + value = self.custom_field_values.get(cf.name) + self.fields[field_name].initial = value + self.instance._cf[cf.name] = value else: self.fields[field_name] = cf.to_form_field() + self.instance._cf[cf.name] = self.fields[field_name].initial # Annotate the field in the list of CustomField form fields self.custom_fields.append(field_name) @@ -77,13 +83,18 @@ class CustomFieldModelForm(forms.ModelForm): cfv.save() def save(self, commit=True): + + # Cache custom field values on object prior to save to ensure change logging + for cf_name in self.custom_fields: + self.instance._cf[cf_name[3:]] = self.cleaned_data.get(cf_name) + obj = super().save(commit) # Handle custom fields the same way we do M2M fields if commit: self._save_custom_fields() else: - self.save_custom_fields = self._save_custom_fields + obj.save_custom_fields = self._save_custom_fields return obj diff --git a/netbox/extras/models/customfields.py b/netbox/extras/models/customfields.py index 62e2ca4df..2671864fb 100644 --- a/netbox/extras/models/customfields.py +++ b/netbox/extras/models/customfields.py @@ -1,4 +1,3 @@ -import logging from collections import OrderedDict from datetime import date diff --git a/netbox/extras/signals.py b/netbox/extras/signals.py index 370f21e43..c5d1a7cf7 100644 --- a/netbox/extras/signals.py +++ b/netbox/extras/signals.py @@ -25,10 +25,6 @@ def _handle_changed_object(request, sender, instance, **kwargs): else: return - # Cache any custom field values to ensure they are captured during serialization - if hasattr(instance, 'cache_custom_fields'): - instance.cache_custom_fields() - # Record an ObjectChange if applicable if hasattr(instance, 'to_objectchange'): objectchange = instance.to_objectchange(action)