diff --git a/admin_confirm/admin.py b/admin_confirm/admin.py index 74ccaf1..0c15eaf 100644 --- a/admin_confirm/admin.py +++ b/admin_confirm/admin.py @@ -1,9 +1,10 @@ +from contextlib import suppress import functools from typing import Dict from django.contrib.admin.exceptions import DisallowedModelAdminToField from django.contrib.admin.utils import flatten_fieldsets, unquote from django.core.cache import cache -from django.core.exceptions import PermissionDenied +from django.core.exceptions import PermissionDenied, FieldDoesNotExist from django.template.response import TemplateResponse from django.contrib.admin.options import TO_FIELD_VAR from django.utils.translation import gettext as _ @@ -175,33 +176,37 @@ def _display_for_changed_data(field, initial_value, new_value): changed_data = {} if add: for name, new_value in form.cleaned_data.items(): - # Don't consider default values as changed for adding - field_object = model._meta.get_field(name) - default_value = field_object.get_default() - if new_value is not None and new_value != default_value: - # Show what the default value is - changed_data[name] = _display_for_changed_data( - field_object, default_value, new_value - ) + # Ignore custom fields + with suppress(FieldDoesNotExist): + # Don't consider default values as changed for adding + field_object = model._meta.get_field(name) + default_value = field_object.get_default() + if new_value is not None and new_value != default_value: + # Show what the default value is + changed_data[name] = _display_for_changed_data( + field_object, default_value, new_value + ) else: # Parse the changed data - Note that using form.changed_data would not work because initial is not set for name, new_value in form.cleaned_data.items(): + # Ignore custom fields + with suppress(FieldDoesNotExist): - # Since the form considers initial as the value first shown in the form - # It could be incorrect when user hits save, and then hits "No, go back to edit" - obj.refresh_from_db() + # Since the form considers initial as the value first shown in the form + # It could be incorrect when user hits save, and then hits "No, go back to edit" + obj.refresh_from_db() - field_object = model._meta.get_field(name) - initial_value = getattr(obj, name) + field_object = model._meta.get_field(name) + initial_value = getattr(obj, name) - # Note: getattr does not work on ManyToManyFields - if isinstance(field_object, ManyToManyField): - initial_value = field_object.value_from_object(obj) + # Note: getattr does not work on ManyToManyFields + if isinstance(field_object, ManyToManyField): + initial_value = field_object.value_from_object(obj) - if initial_value != new_value: - changed_data[name] = _display_for_changed_data( - field_object, initial_value, new_value - ) + if initial_value != new_value: + changed_data[name] = _display_for_changed_data( + field_object, initial_value, new_value + ) return changed_data