Skip to content

Commit

Permalink
fix: avoid exception in changes_display_dict when model is missing (#609
Browse files Browse the repository at this point in the history
)
  • Loading branch information
ppmathis authored Feb 13, 2024
1 parent d78f813 commit e6fc810
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 5 deletions.
17 changes: 12 additions & 5 deletions auditlog/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -436,11 +436,14 @@ def changes_display_dict(self):
"""
:return: The changes recorded in this log entry intended for display to users as a dictionary object.
"""
# Get the model and model_fields
from auditlog.registry import auditlog

# Get the model and model_fields, but gracefully handle the case where the model no longer exists
model = self.content_type.model_class()
model_fields = auditlog.get_model_fields(model._meta.model)
model_fields = None
if auditlog.contains(model._meta.model):
model_fields = auditlog.get_model_fields(model._meta.model)

changes_display_dict = {}
# grab the changes_dict and iterate through
for field_name, values in self.changes_dict.items():
Expand Down Expand Up @@ -501,9 +504,13 @@ def changes_display_dict(self):
value = f"{value[:140]}..."

values_display.append(value)
verbose_name = model_fields["mapping_fields"].get(
field.name, getattr(field, "verbose_name", field.name)
)

# Use verbose_name from mapping if available, otherwise determine from field
if model_fields and field.name in model_fields["mapping_fields"]:
verbose_name = model_fields["mapping_fields"][field.name]
else:
verbose_name = getattr(field, "verbose_name", field.name)

changes_display_dict[verbose_name] = values_display
return changes_display_dict

Expand Down
16 changes: 16 additions & 0 deletions auditlog_tests/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -2613,3 +2613,19 @@ def test_m2m(self):
self.assertEqual(0, LogEntry.objects.get_for_object(recursive).count())
related = ManyRelatedOtherModel.objects.get(pk=1)
self.assertEqual(0, LogEntry.objects.get_for_object(related).count())


class MissingModelTest(TestCase):
def setUp(self):
# Create a log entry, then unregister the model
self.obj = SimpleModel.objects.create(text="I am old.")
auditlog.unregister(SimpleModel)

def tearDown(self):
# Re-register the model for other tests
auditlog.register(SimpleModel)

def test_get_changes_for_missing_model(self):
history = self.obj.history.latest()
self.assertEqual(history.changes_dict["text"][1], self.obj.text)
self.assertEqual(history.changes_display_dict["text"][1], self.obj.text)

0 comments on commit e6fc810

Please sign in to comment.