django-auditlog/auditlog/models.py

613 lines
23 KiB
Python
Raw Normal View History

Fixes #93 - Add 'changes_display_dict' property to 'LogEntry' model to display diff in a more human readable format (#94) Fixes #93 - Add 'changes_display_dict' property to 'LogEntry' model to display diff in a more human readable format 'changes_display_dict' currently handles fields with choices, long textfields and charfields, datefields, timefields, and datetimefields. Supports `django-multiselectfield` with choices and Postgres's ArrayField with choices. Textfields and Charfields longer than 140 characters are truncated with an ellipsis appended. Date, Time and DateTime fields are rendered according to `L10N`, or if turned off fall back on Django settings defaults for DATE_FORMAT, TIME_FORMAT and DATETIME_FORMAT. A new kwarg was added to 'AuditlogModelRegistry' called 'mapping_fields'. The kwarg allows the user to map the fields in the model to a more human readable or intuitive name. If a field isn't mapped it will default to the `verbose_name` as defined on the model or the Django default `verbose_name`. Partial mapping is supported, all fields do not need to be mapped to use the feature. * Add django-multiselectfield test dep * Add psycopg2 test dep * Add postgres testing database and router * Add postgres support to travis builds * Add support for multiple databases. LogEntry saves to same database of the model its associated to * If any literal evals fail default to None * Add support for Postgres ArrayField in changes_display_dict * Revert to old travis image while they are fixing issues with it * Update docs * Add full test coverage
2017-09-13 14:57:47 +00:00
import ast
import contextlib
import json
2022-08-21 19:45:50 +00:00
from copy import deepcopy
from datetime import timezone
2024-10-17 16:40:21 +00:00
from typing import Any, Callable, Union
2013-11-28 04:04:49 +00:00
from dateutil import parser
from dateutil.tz import gettz
from django.conf import settings
from django.contrib.contenttypes.fields import GenericRelation
2013-10-20 13:25:48 +00:00
from django.contrib.contenttypes.models import ContentType
2022-08-21 19:45:50 +00:00
from django.core import serializers
2022-12-28 08:51:44 +00:00
from django.core.exceptions import (
FieldDoesNotExist,
ObjectDoesNotExist,
ValidationError,
)
2020-12-06 20:36:46 +00:00
from django.db import DEFAULT_DB_ALIAS, models
from django.db.models import Q, QuerySet
from django.utils import formats
from django.utils import timezone as django_timezone
from django.utils.encoding import smart_str
from django.utils.translation import gettext_lazy as _
2022-08-21 19:45:50 +00:00
from auditlog.diff import mask_str
DEFAULT_OBJECT_REPR = "<error forming object repr>"
2013-10-20 13:25:48 +00:00
class LogEntryManager(models.Manager):
"""
2015-05-31 13:06:06 +00:00
Custom manager for the :py:class:`LogEntry` model.
2013-10-20 13:25:48 +00:00
"""
Modify ``change`` field to be a json field. (#407) * Modify ``change`` field to be a json field. Storing the object changes as a json is preferred because it allows SQL queries to access the change values. This work moves the burden of handling json objects from an implementation of python's json library in this package and puts it instead onto the ORM. Ultimately, having the text field store the changes was leaving them less accessible to external systems and code that is written outside the scope of the django auditlog. This change was accomplished by updating the field type on the model and then removing the JSON dumps invocations on write and JSON loads invocations on read. Test were updated to assert equality of dictionaries rather than equality of JSON parsable text. Separately, it was asserted that postgres will make these changes to existing data. Therefore, existing postgres installations should update the type of existing field values without issue. * Add test coverage for messages exceeding char len The "Modify change field to be a json field" commit reduced test coverage on the mixins.py file by 0.03%. The reduction in coverage was the result of reducing the number of operations required to achieve the desired state. An additional test was added to increase previously uncovered code. The net effect is an increase in test case coverage. * Add line to changelog Better markdown formatting Co-authored-by: Hasan Ramezani <hasan.r67@gmail.com> * Update CHANGELOG text format More specific language in the improvement section regarding `LogEntry.change` Co-authored-by: Hasan Ramezani <hasan.r67@gmail.com> * Update migration to show Django version 4.0 Co-authored-by: Hasan Ramezani <hasan.r67@gmail.com> * Update CHANGELOG to show breaking change Running the migration to update the field type of `LogEntry.change` is a breaking change. Co-authored-by: Hasan Ramezani <hasan.r67@gmail.com> * Update serial order of migrations * Adjust manager method for compatibility The create log method on the LogEntry manager required an additional kwarg for a call to create an instance regardless of a change or not. This felt brittle anyway. The reason it had worked prior to these changes was that the `change` kwarg was sending a string "null" and not a None when there were no changes. Co-authored-by: Hasan Ramezani <hasan.r67@gmail.com>
2022-12-28 08:50:35 +00:00
def log_create(self, instance, force_log: bool = False, **kwargs):
2013-10-20 13:25:48 +00:00
"""
2022-06-18 16:20:25 +00:00
Helper method to create a new log entry. This method automatically populates some fields when no
explicit value is given.
2015-05-31 13:06:06 +00:00
:param instance: The model instance to log a change for.
:type instance: Model
Modify ``change`` field to be a json field. (#407) * Modify ``change`` field to be a json field. Storing the object changes as a json is preferred because it allows SQL queries to access the change values. This work moves the burden of handling json objects from an implementation of python's json library in this package and puts it instead onto the ORM. Ultimately, having the text field store the changes was leaving them less accessible to external systems and code that is written outside the scope of the django auditlog. This change was accomplished by updating the field type on the model and then removing the JSON dumps invocations on write and JSON loads invocations on read. Test were updated to assert equality of dictionaries rather than equality of JSON parsable text. Separately, it was asserted that postgres will make these changes to existing data. Therefore, existing postgres installations should update the type of existing field values without issue. * Add test coverage for messages exceeding char len The "Modify change field to be a json field" commit reduced test coverage on the mixins.py file by 0.03%. The reduction in coverage was the result of reducing the number of operations required to achieve the desired state. An additional test was added to increase previously uncovered code. The net effect is an increase in test case coverage. * Add line to changelog Better markdown formatting Co-authored-by: Hasan Ramezani <hasan.r67@gmail.com> * Update CHANGELOG text format More specific language in the improvement section regarding `LogEntry.change` Co-authored-by: Hasan Ramezani <hasan.r67@gmail.com> * Update migration to show Django version 4.0 Co-authored-by: Hasan Ramezani <hasan.r67@gmail.com> * Update CHANGELOG to show breaking change Running the migration to update the field type of `LogEntry.change` is a breaking change. Co-authored-by: Hasan Ramezani <hasan.r67@gmail.com> * Update serial order of migrations * Adjust manager method for compatibility The create log method on the LogEntry manager required an additional kwarg for a call to create an instance regardless of a change or not. This felt brittle anyway. The reason it had worked prior to these changes was that the `change` kwarg was sending a string "null" and not a None when there were no changes. Co-authored-by: Hasan Ramezani <hasan.r67@gmail.com>
2022-12-28 08:50:35 +00:00
:param force_log: Create a LogEntry even if no changes exist.
:type force_log: bool
2015-05-31 13:06:06 +00:00
:param kwargs: Field overrides for the :py:class:`LogEntry` object.
:return: The new log entry or `None` if there were no changes.
:rtype: LogEntry
2013-10-20 13:25:48 +00:00
"""
from auditlog.cid import get_cid
2020-12-06 20:29:24 +00:00
changes = kwargs.get("changes", None)
pk = self._get_pk_value(instance)
Modify ``change`` field to be a json field. (#407) * Modify ``change`` field to be a json field. Storing the object changes as a json is preferred because it allows SQL queries to access the change values. This work moves the burden of handling json objects from an implementation of python's json library in this package and puts it instead onto the ORM. Ultimately, having the text field store the changes was leaving them less accessible to external systems and code that is written outside the scope of the django auditlog. This change was accomplished by updating the field type on the model and then removing the JSON dumps invocations on write and JSON loads invocations on read. Test were updated to assert equality of dictionaries rather than equality of JSON parsable text. Separately, it was asserted that postgres will make these changes to existing data. Therefore, existing postgres installations should update the type of existing field values without issue. * Add test coverage for messages exceeding char len The "Modify change field to be a json field" commit reduced test coverage on the mixins.py file by 0.03%. The reduction in coverage was the result of reducing the number of operations required to achieve the desired state. An additional test was added to increase previously uncovered code. The net effect is an increase in test case coverage. * Add line to changelog Better markdown formatting Co-authored-by: Hasan Ramezani <hasan.r67@gmail.com> * Update CHANGELOG text format More specific language in the improvement section regarding `LogEntry.change` Co-authored-by: Hasan Ramezani <hasan.r67@gmail.com> * Update migration to show Django version 4.0 Co-authored-by: Hasan Ramezani <hasan.r67@gmail.com> * Update CHANGELOG to show breaking change Running the migration to update the field type of `LogEntry.change` is a breaking change. Co-authored-by: Hasan Ramezani <hasan.r67@gmail.com> * Update serial order of migrations * Adjust manager method for compatibility The create log method on the LogEntry manager required an additional kwarg for a call to create an instance regardless of a change or not. This felt brittle anyway. The reason it had worked prior to these changes was that the `change` kwarg was sending a string "null" and not a None when there were no changes. Co-authored-by: Hasan Ramezani <hasan.r67@gmail.com>
2022-12-28 08:50:35 +00:00
if changes is not None or force_log:
2020-12-06 20:29:24 +00:00
kwargs.setdefault(
"content_type", ContentType.objects.get_for_model(instance)
)
kwargs.setdefault("object_pk", pk)
try:
object_repr = smart_str(instance)
except ObjectDoesNotExist:
object_repr = DEFAULT_OBJECT_REPR
kwargs.setdefault("object_repr", object_repr)
2022-08-21 19:45:50 +00:00
kwargs.setdefault(
"serialized_data", self._get_serialized_data_or_none(instance)
)
if isinstance(pk, int):
2020-12-06 20:29:24 +00:00
kwargs.setdefault("object_id", pk)
2020-12-06 20:29:24 +00:00
get_additional_data = getattr(instance, "get_additional_data", None)
2015-06-01 16:24:13 +00:00
if callable(get_additional_data):
2020-12-06 20:29:24 +00:00
kwargs.setdefault("additional_data", get_additional_data())
# set correlation id
kwargs.setdefault("cid", get_cid())
return self.create(**kwargs)
return None
def log_m2m_changes(
self, changed_queryset, instance, operation, field_name, **kwargs
):
"""Create a new "changed" log entry from m2m record.
:param changed_queryset: The added or removed related objects.
:type changed_queryset: QuerySet
:param instance: The model instance to log a change for.
:type instance: Model
:param operation: "add" or "delete".
:type action: str
:param field_name: The name of the changed m2m field.
:type field_name: str
:param kwargs: Field overrides for the :py:class:`LogEntry` object.
:return: The new log entry or `None` if there were no changes.
:rtype: LogEntry
"""
from auditlog.cid import get_cid
pk = self._get_pk_value(instance)
if changed_queryset:
kwargs.setdefault(
"content_type", ContentType.objects.get_for_model(instance)
)
kwargs.setdefault("object_pk", pk)
try:
object_repr = smart_str(instance)
except ObjectDoesNotExist:
object_repr = DEFAULT_OBJECT_REPR
kwargs.setdefault("object_repr", object_repr)
kwargs.setdefault("action", LogEntry.Action.UPDATE)
if isinstance(pk, int):
kwargs.setdefault("object_id", pk)
get_additional_data = getattr(instance, "get_additional_data", None)
if callable(get_additional_data):
kwargs.setdefault("additional_data", get_additional_data())
objects = [smart_str(instance) for instance in changed_queryset]
kwargs["changes"] = {
field_name: {
"type": "m2m",
"operation": operation,
"objects": objects,
}
}
kwargs.setdefault("cid", get_cid())
return self.create(**kwargs)
return None
def get_for_object(self, instance):
"""
Get log entries for the specified model instance.
2015-05-31 13:06:06 +00:00
:param instance: The model instance to get log entries for.
:type instance: Model
:return: QuerySet of log entries for the given model instance.
:rtype: QuerySet
"""
# Return empty queryset if the given model instance is not a model instance.
if not isinstance(instance, models.Model):
return self.none()
content_type = ContentType.objects.get_for_model(instance.__class__)
pk = self._get_pk_value(instance)
if isinstance(pk, int):
return self.filter(content_type=content_type, object_id=pk)
else:
return self.filter(content_type=content_type, object_pk=smart_str(pk))
2015-05-15 13:14:57 +00:00
def get_for_objects(self, queryset):
"""
Get log entries for the objects in the specified queryset.
:param queryset: The queryset to get the log entries for.
:type queryset: QuerySet
:return: The LogEntry objects for the objects in the given queryset.
:rtype: QuerySet
"""
if not isinstance(queryset, QuerySet) or queryset.count() == 0:
return self.none()
content_type = ContentType.objects.get_for_model(queryset.model)
2020-12-06 20:29:24 +00:00
primary_keys = list(
queryset.values_list(queryset.model._meta.pk.name, flat=True)
)
2015-05-15 13:14:57 +00:00
if isinstance(primary_keys[0], int):
2020-12-06 20:29:24 +00:00
return (
self.filter(content_type=content_type)
.filter(Q(object_id__in=primary_keys))
.distinct()
)
elif isinstance(queryset.model._meta.pk, models.UUIDField):
primary_keys = [smart_str(pk) for pk in primary_keys]
2020-12-06 20:29:24 +00:00
return (
self.filter(content_type=content_type)
.filter(Q(object_pk__in=primary_keys))
.distinct()
)
else:
2020-12-06 20:29:24 +00:00
return (
self.filter(content_type=content_type)
.filter(Q(object_pk__in=primary_keys))
.distinct()
)
def get_for_model(self, model):
"""
Get log entries for all objects of a specified type.
2015-05-31 13:06:06 +00:00
:param model: The model to get log entries for.
:type model: class
:return: QuerySet of log entries for the given model.
:rtype: QuerySet
"""
# Return empty queryset if the given object is not valid.
if not issubclass(model, models.Model):
return self.none()
2013-11-28 04:04:49 +00:00
content_type = ContentType.objects.get_for_model(model)
return self.filter(content_type=content_type)
2013-10-20 13:25:48 +00:00
def _get_pk_value(self, instance):
"""
Get the primary key field value for a model instance.
2015-05-31 13:06:06 +00:00
:param instance: The model instance to get the primary key for.
:type instance: Model
:return: The primary key value of the given model instance.
"""
# Should be equivalent to `instance.pk`.
pk_field = instance._meta.pk.attname
pk = getattr(instance, pk_field, None)
# Check to make sure that we got a pk not a model object.
# Should be guaranteed as we used `attname` above, not `name`.
assert not isinstance(pk, models.Model)
return pk
2022-08-21 19:45:50 +00:00
def _get_serialized_data_or_none(self, instance):
from auditlog.registry import auditlog
if not auditlog.contains(instance.__class__):
return None
2022-08-21 19:45:50 +00:00
opts = auditlog.get_serialize_options(instance.__class__)
if not opts["serialize_data"]:
return None
model_fields = auditlog.get_model_fields(instance.__class__)
kwargs = opts.get("serialize_kwargs", {})
if opts["serialize_auditlog_fields_only"]:
kwargs.setdefault(
"fields", self._get_applicable_model_fields(instance, model_fields)
)
instance_copy = self._get_copy_with_python_typed_fields(instance)
data = dict(
json.loads(serializers.serialize("json", (instance_copy,), **kwargs))[0]
)
mask_fields = model_fields["mask_fields"]
if mask_fields:
data = self._mask_serialized_fields(data, mask_fields)
return data
def _get_copy_with_python_typed_fields(self, instance):
"""
Attempt to create copy of instance and coerce types on instance fields
The Django core serializer assumes that the values on object fields are
correctly typed to their respective fields. Updates made to an object's
in-memory state may not meet this assumption. To prevent this violation, values
are typed by calling `to_python` from the field object, the result is set on a
copy of the instance and the copy is sent to the serializer.
"""
try:
instance_copy = deepcopy(instance)
except TypeError:
instance_copy = instance
for field in instance_copy._meta.fields:
if not field.is_relation:
value = getattr(instance_copy, field.name)
try:
setattr(instance_copy, field.name, field.to_python(value))
except ValidationError:
continue
2022-08-21 19:45:50 +00:00
return instance_copy
def _get_applicable_model_fields(
2024-10-17 16:40:21 +00:00
self, instance, model_fields: dict[str, list[str]]
) -> list[str]:
2022-08-21 19:45:50 +00:00
include_fields = model_fields["include_fields"]
exclude_fields = model_fields["exclude_fields"]
all_field_names = [field.name for field in instance._meta.fields]
if not include_fields and not exclude_fields:
return all_field_names
return list(set(include_fields or all_field_names).difference(exclude_fields))
def _mask_serialized_fields(
2024-10-17 16:40:21 +00:00
self, data: dict[str, Any], mask_fields: list[str]
) -> dict[str, Any]:
2022-08-21 19:45:50 +00:00
all_field_data = data.pop("fields")
masked_field_data = {}
for key, value in all_field_data.items():
if isinstance(value, str) and key in mask_fields:
masked_field_data[key] = mask_str(value)
else:
masked_field_data[key] = value
data["fields"] = masked_field_data
return data
2013-10-20 13:25:48 +00:00
class LogEntry(models.Model):
"""
2022-06-18 16:20:25 +00:00
Represents an entry in the audit log. The content type is saved along with the textual and numeric
(if available) primary key, as well as the textual representation of the object when it was saved.
It holds the action performed and the fields that were changed in the transaction.
2013-10-23 15:23:52 +00:00
2022-06-18 16:20:25 +00:00
If AuditlogMiddleware is used, the actor will be set automatically. Keep in mind that
editing / re-saving LogEntry instances may set the actor to a wrong value - editing LogEntry
instances is not recommended (and it should not be necessary).
2013-10-20 13:25:48 +00:00
"""
class Action:
2014-03-14 16:15:31 +00:00
"""
2022-06-18 16:20:25 +00:00
The actions that Auditlog distinguishes: creating, updating and deleting objects. Viewing objects
is not logged. The values of the actions are numeric, a higher integer value means a more intrusive
action. This may be useful in some cases when comparing actions because the ``__lt``, ``__lte``,
``__gt``, ``__gte`` lookup filters can be used in queries.
2015-05-31 13:06:06 +00:00
The valid actions are :py:attr:`Action.CREATE`, :py:attr:`Action.UPDATE`,
:py:attr:`Action.DELETE` and :py:attr:`Action.ACCESS`.
2014-03-14 16:15:31 +00:00
"""
2020-12-06 20:29:24 +00:00
2013-10-20 13:25:48 +00:00
CREATE = 0
UPDATE = 1
DELETE = 2
ACCESS = 3
2013-10-20 13:25:48 +00:00
choices = (
(CREATE, _("create")),
(UPDATE, _("update")),
(DELETE, _("delete")),
(ACCESS, _("access")),
2013-10-20 13:25:48 +00:00
)
2020-12-06 20:29:24 +00:00
content_type = models.ForeignKey(
to="contenttypes.ContentType",
on_delete=models.CASCADE,
related_name="+",
verbose_name=_("content type"),
)
object_pk = models.CharField(
db_index=True, max_length=255, verbose_name=_("object pk")
)
object_id = models.BigIntegerField(
blank=True, db_index=True, null=True, verbose_name=_("object id")
)
2013-10-20 13:25:48 +00:00
object_repr = models.TextField(verbose_name=_("object representation"))
2022-08-21 19:45:50 +00:00
serialized_data = models.JSONField(null=True)
2020-12-06 20:29:24 +00:00
action = models.PositiveSmallIntegerField(
choices=Action.choices, verbose_name=_("action"), db_index=True
2020-12-06 20:29:24 +00:00
)
changes_text = models.TextField(blank=True, verbose_name=_("change message"))
Modify ``change`` field to be a json field. (#407) * Modify ``change`` field to be a json field. Storing the object changes as a json is preferred because it allows SQL queries to access the change values. This work moves the burden of handling json objects from an implementation of python's json library in this package and puts it instead onto the ORM. Ultimately, having the text field store the changes was leaving them less accessible to external systems and code that is written outside the scope of the django auditlog. This change was accomplished by updating the field type on the model and then removing the JSON dumps invocations on write and JSON loads invocations on read. Test were updated to assert equality of dictionaries rather than equality of JSON parsable text. Separately, it was asserted that postgres will make these changes to existing data. Therefore, existing postgres installations should update the type of existing field values without issue. * Add test coverage for messages exceeding char len The "Modify change field to be a json field" commit reduced test coverage on the mixins.py file by 0.03%. The reduction in coverage was the result of reducing the number of operations required to achieve the desired state. An additional test was added to increase previously uncovered code. The net effect is an increase in test case coverage. * Add line to changelog Better markdown formatting Co-authored-by: Hasan Ramezani <hasan.r67@gmail.com> * Update CHANGELOG text format More specific language in the improvement section regarding `LogEntry.change` Co-authored-by: Hasan Ramezani <hasan.r67@gmail.com> * Update migration to show Django version 4.0 Co-authored-by: Hasan Ramezani <hasan.r67@gmail.com> * Update CHANGELOG to show breaking change Running the migration to update the field type of `LogEntry.change` is a breaking change. Co-authored-by: Hasan Ramezani <hasan.r67@gmail.com> * Update serial order of migrations * Adjust manager method for compatibility The create log method on the LogEntry manager required an additional kwarg for a call to create an instance regardless of a change or not. This felt brittle anyway. The reason it had worked prior to these changes was that the `change` kwarg was sending a string "null" and not a None when there were no changes. Co-authored-by: Hasan Ramezani <hasan.r67@gmail.com>
2022-12-28 08:50:35 +00:00
changes = models.JSONField(null=True, verbose_name=_("change message"))
2020-12-06 20:29:24 +00:00
actor = models.ForeignKey(
to=settings.AUTH_USER_MODEL,
on_delete=models.SET_NULL,
blank=True,
null=True,
related_name="+",
verbose_name=_("actor"),
)
cid = models.CharField(
max_length=255,
db_index=True,
blank=True,
null=True,
verbose_name=_("Correlation ID"),
)
2020-12-06 20:29:24 +00:00
remote_addr = models.GenericIPAddressField(
blank=True, null=True, verbose_name=_("remote address")
)
2024-10-07 13:52:34 +00:00
remote_port = models.PositiveIntegerField(
blank=True, null=True, verbose_name=_("remote port")
)
timestamp = models.DateTimeField(
default=django_timezone.now,
db_index=True,
verbose_name=_("timestamp"),
)
2022-04-05 11:57:17 +00:00
additional_data = models.JSONField(
2020-12-06 20:29:24 +00:00
blank=True, null=True, verbose_name=_("additional data")
)
2013-10-20 13:25:48 +00:00
objects = LogEntryManager()
2013-10-20 13:25:48 +00:00
class Meta:
2020-12-06 20:29:24 +00:00
get_latest_by = "timestamp"
ordering = ["-timestamp"]
2013-10-20 13:25:48 +00:00
verbose_name = _("log entry")
verbose_name_plural = _("log entries")
def __str__(self):
2013-10-20 13:25:48 +00:00
if self.action == self.Action.CREATE:
fstring = _("Created {repr:s}")
2013-10-20 13:25:48 +00:00
elif self.action == self.Action.UPDATE:
fstring = _("Updated {repr:s}")
2013-10-20 13:25:48 +00:00
elif self.action == self.Action.DELETE:
fstring = _("Deleted {repr:s}")
2013-10-20 13:25:48 +00:00
else:
fstring = _("Logged {repr:s}")
return fstring.format(repr=self.object_repr)
@property
def changes_dict(self):
2013-12-18 16:27:11 +00:00
"""
2015-05-14 23:25:44 +00:00
:return: The changes recorded in this log entry as a dictionary object.
2013-12-18 16:27:11 +00:00
"""
return changes_func(self)
@property
2020-12-06 20:29:24 +00:00
def changes_str(self, colon=": ", arrow=" \u2192 ", separator="; "):
2013-12-18 16:27:11 +00:00
"""
2022-06-18 16:20:25 +00:00
Return the changes recorded in this log entry as a string. The formatting of the string can be
customized by setting alternate values for colon, arrow and separator. If the formatting is still
not satisfying, please use :py:func:`LogEntry.changes_dict` and format the string yourself.
2015-05-14 23:25:44 +00:00
:param colon: The string to place between the field name and the values.
:param arrow: The string to place between each old and new value.
:param separator: The string to place between each field.
:return: A readable string of the changes in this log entry.
2013-12-18 16:27:11 +00:00
"""
substrings = []
for field, values in self.changes_dict.items():
2020-12-06 20:29:24 +00:00
substring = "{field_name:s}{colon:s}{old:s}{arrow:s}{new:s}".format(
field_name=field,
colon=colon,
old=values[0],
arrow=arrow,
new=values[1],
)
substrings.append(substring)
return separator.join(substrings)
Fixes #93 - Add 'changes_display_dict' property to 'LogEntry' model to display diff in a more human readable format (#94) Fixes #93 - Add 'changes_display_dict' property to 'LogEntry' model to display diff in a more human readable format 'changes_display_dict' currently handles fields with choices, long textfields and charfields, datefields, timefields, and datetimefields. Supports `django-multiselectfield` with choices and Postgres's ArrayField with choices. Textfields and Charfields longer than 140 characters are truncated with an ellipsis appended. Date, Time and DateTime fields are rendered according to `L10N`, or if turned off fall back on Django settings defaults for DATE_FORMAT, TIME_FORMAT and DATETIME_FORMAT. A new kwarg was added to 'AuditlogModelRegistry' called 'mapping_fields'. The kwarg allows the user to map the fields in the model to a more human readable or intuitive name. If a field isn't mapped it will default to the `verbose_name` as defined on the model or the Django default `verbose_name`. Partial mapping is supported, all fields do not need to be mapped to use the feature. * Add django-multiselectfield test dep * Add psycopg2 test dep * Add postgres testing database and router * Add postgres support to travis builds * Add support for multiple databases. LogEntry saves to same database of the model its associated to * If any literal evals fail default to None * Add support for Postgres ArrayField in changes_display_dict * Revert to old travis image while they are fixing issues with it * Update docs * Add full test coverage
2017-09-13 14:57:47 +00:00
@property
def changes_display_dict(self):
"""
:return: The changes recorded in this log entry intended for display to users as a dictionary object.
"""
from auditlog.registry import auditlog
2020-12-06 20:29:24 +00:00
# Get the model and model_fields, but gracefully handle the case where the model no longer exists
Fixes #93 - Add 'changes_display_dict' property to 'LogEntry' model to display diff in a more human readable format (#94) Fixes #93 - Add 'changes_display_dict' property to 'LogEntry' model to display diff in a more human readable format 'changes_display_dict' currently handles fields with choices, long textfields and charfields, datefields, timefields, and datetimefields. Supports `django-multiselectfield` with choices and Postgres's ArrayField with choices. Textfields and Charfields longer than 140 characters are truncated with an ellipsis appended. Date, Time and DateTime fields are rendered according to `L10N`, or if turned off fall back on Django settings defaults for DATE_FORMAT, TIME_FORMAT and DATETIME_FORMAT. A new kwarg was added to 'AuditlogModelRegistry' called 'mapping_fields'. The kwarg allows the user to map the fields in the model to a more human readable or intuitive name. If a field isn't mapped it will default to the `verbose_name` as defined on the model or the Django default `verbose_name`. Partial mapping is supported, all fields do not need to be mapped to use the feature. * Add django-multiselectfield test dep * Add psycopg2 test dep * Add postgres testing database and router * Add postgres support to travis builds * Add support for multiple databases. LogEntry saves to same database of the model its associated to * If any literal evals fail default to None * Add support for Postgres ArrayField in changes_display_dict * Revert to old travis image while they are fixing issues with it * Update docs * Add full test coverage
2017-09-13 14:57:47 +00:00
model = self.content_type.model_class()
model_fields = None
if auditlog.contains(model._meta.model):
model_fields = auditlog.get_model_fields(model._meta.model)
Fixes #93 - Add 'changes_display_dict' property to 'LogEntry' model to display diff in a more human readable format (#94) Fixes #93 - Add 'changes_display_dict' property to 'LogEntry' model to display diff in a more human readable format 'changes_display_dict' currently handles fields with choices, long textfields and charfields, datefields, timefields, and datetimefields. Supports `django-multiselectfield` with choices and Postgres's ArrayField with choices. Textfields and Charfields longer than 140 characters are truncated with an ellipsis appended. Date, Time and DateTime fields are rendered according to `L10N`, or if turned off fall back on Django settings defaults for DATE_FORMAT, TIME_FORMAT and DATETIME_FORMAT. A new kwarg was added to 'AuditlogModelRegistry' called 'mapping_fields'. The kwarg allows the user to map the fields in the model to a more human readable or intuitive name. If a field isn't mapped it will default to the `verbose_name` as defined on the model or the Django default `verbose_name`. Partial mapping is supported, all fields do not need to be mapped to use the feature. * Add django-multiselectfield test dep * Add psycopg2 test dep * Add postgres testing database and router * Add postgres support to travis builds * Add support for multiple databases. LogEntry saves to same database of the model its associated to * If any literal evals fail default to None * Add support for Postgres ArrayField in changes_display_dict * Revert to old travis image while they are fixing issues with it * Update docs * Add full test coverage
2017-09-13 14:57:47 +00:00
changes_display_dict = {}
# grab the changes_dict and iterate through
for field_name, values in self.changes_dict.items():
Fixes #93 - Add 'changes_display_dict' property to 'LogEntry' model to display diff in a more human readable format (#94) Fixes #93 - Add 'changes_display_dict' property to 'LogEntry' model to display diff in a more human readable format 'changes_display_dict' currently handles fields with choices, long textfields and charfields, datefields, timefields, and datetimefields. Supports `django-multiselectfield` with choices and Postgres's ArrayField with choices. Textfields and Charfields longer than 140 characters are truncated with an ellipsis appended. Date, Time and DateTime fields are rendered according to `L10N`, or if turned off fall back on Django settings defaults for DATE_FORMAT, TIME_FORMAT and DATETIME_FORMAT. A new kwarg was added to 'AuditlogModelRegistry' called 'mapping_fields'. The kwarg allows the user to map the fields in the model to a more human readable or intuitive name. If a field isn't mapped it will default to the `verbose_name` as defined on the model or the Django default `verbose_name`. Partial mapping is supported, all fields do not need to be mapped to use the feature. * Add django-multiselectfield test dep * Add psycopg2 test dep * Add postgres testing database and router * Add postgres support to travis builds * Add support for multiple databases. LogEntry saves to same database of the model its associated to * If any literal evals fail default to None * Add support for Postgres ArrayField in changes_display_dict * Revert to old travis image while they are fixing issues with it * Update docs * Add full test coverage
2017-09-13 14:57:47 +00:00
# try to get the field attribute on the model
try:
field = model._meta.get_field(field_name)
except FieldDoesNotExist:
changes_display_dict[field_name] = values
continue
values_display = []
# handle choices fields and Postgres ArrayField to get human-readable version
choices_dict = None
if getattr(field, "choices", []):
choices_dict = dict(field.choices)
if getattr(getattr(field, "base_field", None), "choices", []):
choices_dict = dict(field.base_field.choices)
if choices_dict:
Fixes #93 - Add 'changes_display_dict' property to 'LogEntry' model to display diff in a more human readable format (#94) Fixes #93 - Add 'changes_display_dict' property to 'LogEntry' model to display diff in a more human readable format 'changes_display_dict' currently handles fields with choices, long textfields and charfields, datefields, timefields, and datetimefields. Supports `django-multiselectfield` with choices and Postgres's ArrayField with choices. Textfields and Charfields longer than 140 characters are truncated with an ellipsis appended. Date, Time and DateTime fields are rendered according to `L10N`, or if turned off fall back on Django settings defaults for DATE_FORMAT, TIME_FORMAT and DATETIME_FORMAT. A new kwarg was added to 'AuditlogModelRegistry' called 'mapping_fields'. The kwarg allows the user to map the fields in the model to a more human readable or intuitive name. If a field isn't mapped it will default to the `verbose_name` as defined on the model or the Django default `verbose_name`. Partial mapping is supported, all fields do not need to be mapped to use the feature. * Add django-multiselectfield test dep * Add psycopg2 test dep * Add postgres testing database and router * Add postgres support to travis builds * Add support for multiple databases. LogEntry saves to same database of the model its associated to * If any literal evals fail default to None * Add support for Postgres ArrayField in changes_display_dict * Revert to old travis image while they are fixing issues with it * Update docs * Add full test coverage
2017-09-13 14:57:47 +00:00
for value in values:
try:
value = ast.literal_eval(value)
if type(value) is [].__class__:
2020-12-06 20:29:24 +00:00
values_display.append(
", ".join(
[choices_dict.get(val, "None") for val in value]
)
)
Fixes #93 - Add 'changes_display_dict' property to 'LogEntry' model to display diff in a more human readable format (#94) Fixes #93 - Add 'changes_display_dict' property to 'LogEntry' model to display diff in a more human readable format 'changes_display_dict' currently handles fields with choices, long textfields and charfields, datefields, timefields, and datetimefields. Supports `django-multiselectfield` with choices and Postgres's ArrayField with choices. Textfields and Charfields longer than 140 characters are truncated with an ellipsis appended. Date, Time and DateTime fields are rendered according to `L10N`, or if turned off fall back on Django settings defaults for DATE_FORMAT, TIME_FORMAT and DATETIME_FORMAT. A new kwarg was added to 'AuditlogModelRegistry' called 'mapping_fields'. The kwarg allows the user to map the fields in the model to a more human readable or intuitive name. If a field isn't mapped it will default to the `verbose_name` as defined on the model or the Django default `verbose_name`. Partial mapping is supported, all fields do not need to be mapped to use the feature. * Add django-multiselectfield test dep * Add psycopg2 test dep * Add postgres testing database and router * Add postgres support to travis builds * Add support for multiple databases. LogEntry saves to same database of the model its associated to * If any literal evals fail default to None * Add support for Postgres ArrayField in changes_display_dict * Revert to old travis image while they are fixing issues with it * Update docs * Add full test coverage
2017-09-13 14:57:47 +00:00
else:
2020-12-06 20:29:24 +00:00
values_display.append(choices_dict.get(value, "None"))
2022-06-18 16:20:25 +00:00
except Exception:
2020-12-06 20:29:24 +00:00
values_display.append(choices_dict.get(value, "None"))
Fixes #93 - Add 'changes_display_dict' property to 'LogEntry' model to display diff in a more human readable format (#94) Fixes #93 - Add 'changes_display_dict' property to 'LogEntry' model to display diff in a more human readable format 'changes_display_dict' currently handles fields with choices, long textfields and charfields, datefields, timefields, and datetimefields. Supports `django-multiselectfield` with choices and Postgres's ArrayField with choices. Textfields and Charfields longer than 140 characters are truncated with an ellipsis appended. Date, Time and DateTime fields are rendered according to `L10N`, or if turned off fall back on Django settings defaults for DATE_FORMAT, TIME_FORMAT and DATETIME_FORMAT. A new kwarg was added to 'AuditlogModelRegistry' called 'mapping_fields'. The kwarg allows the user to map the fields in the model to a more human readable or intuitive name. If a field isn't mapped it will default to the `verbose_name` as defined on the model or the Django default `verbose_name`. Partial mapping is supported, all fields do not need to be mapped to use the feature. * Add django-multiselectfield test dep * Add psycopg2 test dep * Add postgres testing database and router * Add postgres support to travis builds * Add support for multiple databases. LogEntry saves to same database of the model its associated to * If any literal evals fail default to None * Add support for Postgres ArrayField in changes_display_dict * Revert to old travis image while they are fixing issues with it * Update docs * Add full test coverage
2017-09-13 14:57:47 +00:00
else:
try:
field_type = field.get_internal_type()
except AttributeError:
# if the field is a relationship it has no internal type and exclude it
continue
Fixes #93 - Add 'changes_display_dict' property to 'LogEntry' model to display diff in a more human readable format (#94) Fixes #93 - Add 'changes_display_dict' property to 'LogEntry' model to display diff in a more human readable format 'changes_display_dict' currently handles fields with choices, long textfields and charfields, datefields, timefields, and datetimefields. Supports `django-multiselectfield` with choices and Postgres's ArrayField with choices. Textfields and Charfields longer than 140 characters are truncated with an ellipsis appended. Date, Time and DateTime fields are rendered according to `L10N`, or if turned off fall back on Django settings defaults for DATE_FORMAT, TIME_FORMAT and DATETIME_FORMAT. A new kwarg was added to 'AuditlogModelRegistry' called 'mapping_fields'. The kwarg allows the user to map the fields in the model to a more human readable or intuitive name. If a field isn't mapped it will default to the `verbose_name` as defined on the model or the Django default `verbose_name`. Partial mapping is supported, all fields do not need to be mapped to use the feature. * Add django-multiselectfield test dep * Add psycopg2 test dep * Add postgres testing database and router * Add postgres support to travis builds * Add support for multiple databases. LogEntry saves to same database of the model its associated to * If any literal evals fail default to None * Add support for Postgres ArrayField in changes_display_dict * Revert to old travis image while they are fixing issues with it * Update docs * Add full test coverage
2017-09-13 14:57:47 +00:00
for value in values:
# handle case where field is a datetime, date, or time type
if field_type in ["DateTimeField", "DateField", "TimeField"]:
try:
value = parser.parse(value)
if field_type == "DateField":
value = value.date()
elif field_type == "TimeField":
value = value.time()
elif field_type == "DateTimeField":
value = value.replace(tzinfo=timezone.utc)
value = value.astimezone(gettz(settings.TIME_ZONE))
Fixes #93 - Add 'changes_display_dict' property to 'LogEntry' model to display diff in a more human readable format (#94) Fixes #93 - Add 'changes_display_dict' property to 'LogEntry' model to display diff in a more human readable format 'changes_display_dict' currently handles fields with choices, long textfields and charfields, datefields, timefields, and datetimefields. Supports `django-multiselectfield` with choices and Postgres's ArrayField with choices. Textfields and Charfields longer than 140 characters are truncated with an ellipsis appended. Date, Time and DateTime fields are rendered according to `L10N`, or if turned off fall back on Django settings defaults for DATE_FORMAT, TIME_FORMAT and DATETIME_FORMAT. A new kwarg was added to 'AuditlogModelRegistry' called 'mapping_fields'. The kwarg allows the user to map the fields in the model to a more human readable or intuitive name. If a field isn't mapped it will default to the `verbose_name` as defined on the model or the Django default `verbose_name`. Partial mapping is supported, all fields do not need to be mapped to use the feature. * Add django-multiselectfield test dep * Add psycopg2 test dep * Add postgres testing database and router * Add postgres support to travis builds * Add support for multiple databases. LogEntry saves to same database of the model its associated to * If any literal evals fail default to None * Add support for Postgres ArrayField in changes_display_dict * Revert to old travis image while they are fixing issues with it * Update docs * Add full test coverage
2017-09-13 14:57:47 +00:00
value = formats.localize(value)
except ValueError:
pass
2022-12-28 08:51:44 +00:00
elif field_type in ["ForeignKey", "OneToOneField"]:
value = self._get_changes_display_for_fk_field(field, value)
Fixes #93 - Add 'changes_display_dict' property to 'LogEntry' model to display diff in a more human readable format (#94) Fixes #93 - Add 'changes_display_dict' property to 'LogEntry' model to display diff in a more human readable format 'changes_display_dict' currently handles fields with choices, long textfields and charfields, datefields, timefields, and datetimefields. Supports `django-multiselectfield` with choices and Postgres's ArrayField with choices. Textfields and Charfields longer than 140 characters are truncated with an ellipsis appended. Date, Time and DateTime fields are rendered according to `L10N`, or if turned off fall back on Django settings defaults for DATE_FORMAT, TIME_FORMAT and DATETIME_FORMAT. A new kwarg was added to 'AuditlogModelRegistry' called 'mapping_fields'. The kwarg allows the user to map the fields in the model to a more human readable or intuitive name. If a field isn't mapped it will default to the `verbose_name` as defined on the model or the Django default `verbose_name`. Partial mapping is supported, all fields do not need to be mapped to use the feature. * Add django-multiselectfield test dep * Add psycopg2 test dep * Add postgres testing database and router * Add postgres support to travis builds * Add support for multiple databases. LogEntry saves to same database of the model its associated to * If any literal evals fail default to None * Add support for Postgres ArrayField in changes_display_dict * Revert to old travis image while they are fixing issues with it * Update docs * Add full test coverage
2017-09-13 14:57:47 +00:00
# check if length is longer than 140 and truncate with ellipsis
if len(value) > 140:
2022-01-07 21:37:18 +00:00
value = f"{value[:140]}..."
Fixes #93 - Add 'changes_display_dict' property to 'LogEntry' model to display diff in a more human readable format (#94) Fixes #93 - Add 'changes_display_dict' property to 'LogEntry' model to display diff in a more human readable format 'changes_display_dict' currently handles fields with choices, long textfields and charfields, datefields, timefields, and datetimefields. Supports `django-multiselectfield` with choices and Postgres's ArrayField with choices. Textfields and Charfields longer than 140 characters are truncated with an ellipsis appended. Date, Time and DateTime fields are rendered according to `L10N`, or if turned off fall back on Django settings defaults for DATE_FORMAT, TIME_FORMAT and DATETIME_FORMAT. A new kwarg was added to 'AuditlogModelRegistry' called 'mapping_fields'. The kwarg allows the user to map the fields in the model to a more human readable or intuitive name. If a field isn't mapped it will default to the `verbose_name` as defined on the model or the Django default `verbose_name`. Partial mapping is supported, all fields do not need to be mapped to use the feature. * Add django-multiselectfield test dep * Add psycopg2 test dep * Add postgres testing database and router * Add postgres support to travis builds * Add support for multiple databases. LogEntry saves to same database of the model its associated to * If any literal evals fail default to None * Add support for Postgres ArrayField in changes_display_dict * Revert to old travis image while they are fixing issues with it * Update docs * Add full test coverage
2017-09-13 14:57:47 +00:00
values_display.append(value)
# 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)
Fixes #93 - Add 'changes_display_dict' property to 'LogEntry' model to display diff in a more human readable format (#94) Fixes #93 - Add 'changes_display_dict' property to 'LogEntry' model to display diff in a more human readable format 'changes_display_dict' currently handles fields with choices, long textfields and charfields, datefields, timefields, and datetimefields. Supports `django-multiselectfield` with choices and Postgres's ArrayField with choices. Textfields and Charfields longer than 140 characters are truncated with an ellipsis appended. Date, Time and DateTime fields are rendered according to `L10N`, or if turned off fall back on Django settings defaults for DATE_FORMAT, TIME_FORMAT and DATETIME_FORMAT. A new kwarg was added to 'AuditlogModelRegistry' called 'mapping_fields'. The kwarg allows the user to map the fields in the model to a more human readable or intuitive name. If a field isn't mapped it will default to the `verbose_name` as defined on the model or the Django default `verbose_name`. Partial mapping is supported, all fields do not need to be mapped to use the feature. * Add django-multiselectfield test dep * Add psycopg2 test dep * Add postgres testing database and router * Add postgres support to travis builds * Add support for multiple databases. LogEntry saves to same database of the model its associated to * If any literal evals fail default to None * Add support for Postgres ArrayField in changes_display_dict * Revert to old travis image while they are fixing issues with it * Update docs * Add full test coverage
2017-09-13 14:57:47 +00:00
changes_display_dict[verbose_name] = values_display
return changes_display_dict
2022-12-28 08:51:44 +00:00
def _get_changes_display_for_fk_field(
self, field: Union[models.ForeignKey, models.OneToOneField], value: Any
) -> str:
"""
:return: A string representing a given FK value and the field to which it belongs
"""
# Return "None" if the FK value is "None".
if value == "None":
return value
# Attempt to convert given value to the PK type for the related model
try:
pk_value = field.related_model._meta.pk.to_python(value)
# ValidationError will handle legacy values where string representations were
# stored rather than PKs. This will also handle cases where the PK type is
# changed between the time the LogEntry is created and this method is called.
except ValidationError:
return value
# Attempt to return the string representation of the object
try:
return smart_str(field.related_model.objects.get(pk=pk_value))
# ObjectDoesNotExist will be raised if the object was deleted.
except ObjectDoesNotExist:
return f"Deleted '{field.related_model.__name__}' ({value})"
2013-10-20 13:25:48 +00:00
class AuditlogHistoryField(GenericRelation):
2013-10-20 13:25:48 +00:00
"""
2022-06-18 16:20:25 +00:00
A subclass of py:class:`django.contrib.contenttypes.fields.GenericRelation` that sets some default
variables. This makes it easier to access Auditlog's log entries, for example in templates.
2013-10-23 15:23:52 +00:00
By default, this field will assume that your primary keys are numeric, simply because this is the most
2022-06-18 16:20:25 +00:00
common case. However, if you have a non-integer primary key, you can simply pass ``pk_indexable=False``
to the constructor, and Auditlog will fall back to using a non-indexed text based field for this model.
2014-03-14 16:15:31 +00:00
2022-06-18 16:20:25 +00:00
Using this field will not automatically register the model for automatic logging. This is done so you
can be more flexible with how you use this field.
2015-05-31 13:06:06 +00:00
:param pk_indexable: Whether the primary key for this model is not an :py:class:`int` or :py:class:`long`.
:type pk_indexable: bool
:param delete_related: Delete referenced auditlog entries together with the tracked object.
Defaults to False to keep the integrity of the auditlog.
:type delete_related: bool
2013-10-20 13:25:48 +00:00
"""
def __init__(self, pk_indexable=True, delete_related=False, **kwargs):
2020-12-06 20:29:24 +00:00
kwargs["to"] = LogEntry
if pk_indexable:
2020-12-06 20:29:24 +00:00
kwargs["object_id_field"] = "object_id"
else:
2020-12-06 20:29:24 +00:00
kwargs["object_id_field"] = "object_pk"
2020-12-06 20:29:24 +00:00
kwargs["content_type_field"] = "content_type"
self.delete_related = delete_related
2022-01-07 21:37:18 +00:00
super().__init__(**kwargs)
def bulk_related_objects(self, objs, using=DEFAULT_DB_ALIAS):
"""
Return all objects related to ``objs`` via this ``GenericRelation``.
"""
if self.delete_related:
2022-01-07 21:37:18 +00:00
return super().bulk_related_objects(objs, using)
# When deleting, Collector.collect() finds related objects using this
# method. However, because we don't want to delete these related
# objects, we simply return an empty list.
return []
# should I add a signal receiver for setting_changed?
changes_func = None
2024-10-17 16:40:21 +00:00
def _changes_func() -> Callable[[LogEntry], dict]:
def json_then_text(instance: LogEntry) -> dict:
if instance.changes:
return instance.changes
elif instance.changes_text:
with contextlib.suppress(ValueError):
return json.loads(instance.changes_text)
return {}
2024-10-17 16:40:21 +00:00
def default(instance: LogEntry) -> dict:
return instance.changes or {}
if settings.AUDITLOG_USE_TEXT_CHANGES_IF_JSON_IS_NOT_PRESENT:
return json_then_text
return default