Fix AttributeError when AUDITLOG_LOGENTRY_MODEL is not set (#788) (#789)

Use getattr() with default value in get_logentry_model() to handle
cases where conf.py hasn't been imported yet due to import order.

Adds regression test to verify the fix.
This commit is contained in:
James Gillard 2025-12-12 15:28:10 +00:00 committed by GitHub
parent 66125030a8
commit dc636716b0
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 22 additions and 4 deletions

View file

@ -10,10 +10,9 @@ __version__ = version("django-auditlog")
def get_logentry_model():
model_string = getattr(settings, "AUDITLOG_LOGENTRY_MODEL", "auditlog.LogEntry")
try:
return django_apps.get_model(
settings.AUDITLOG_LOGENTRY_MODEL, require_ready=False
)
return django_apps.get_model(model_string, require_ready=False)
except ValueError:
raise ImproperlyConfigured(
"AUDITLOG_LOGENTRY_MODEL must be of the form 'app_label.model_name'"
@ -21,5 +20,5 @@ def get_logentry_model():
except LookupError:
raise ImproperlyConfigured(
"AUDITLOG_LOGENTRY_MODEL refers to model '%s' that has not been installed"
% settings.AUDITLOG_LOGENTRY_MODEL
% model_string
)

View file

@ -3248,3 +3248,22 @@ class GetLogEntryModelTest(TestCase):
def test_invalid_appname(self):
with self.assertRaises(ImproperlyConfigured):
get_logentry_model()
def test_logentry_model_default_when_setting_missing(self):
"""Regression test for issue #788: AttributeError when AUDITLOG_LOGENTRY_MODEL is not set."""
# Save and remove the setting to simulate the bug condition
original_value = getattr(settings, "AUDITLOG_LOGENTRY_MODEL", None)
if hasattr(settings, "AUDITLOG_LOGENTRY_MODEL"):
delattr(settings, "AUDITLOG_LOGENTRY_MODEL")
try:
# This should NOT raise AttributeError - it should use the default
model = get_logentry_model()
self.assertEqual(
f"{model._meta.app_label}.{model._meta.object_name}",
"auditlog.LogEntry",
)
finally:
# Restore the original setting
if original_value is not None:
settings.AUDITLOG_LOGENTRY_MODEL = original_value