Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# Imports
3import difflib
4from django.conf import settings
5from django.db import models
6from django.utils.translation import ugettext_lazy as _
7from superdjango.db.history.models import HistoryModel
9# Exports
11__all__ = (
12 "History",
13)
15# Constants
17AUTH_USER_MODEL = settings.AUTH_USER_MODEL
19# Models
22class History(HistoryModel):
23 """An entry in the record history timeline."""
25 field_changes = models.TextField(
26 _("field changes"),
27 blank=True,
28 help_text=_("Fields that changed as part of the history."),
29 null=True
30 )
32 class Meta:
33 get_latest_by = "added_dt"
34 ordering = ["-added_dt"]
35 verbose_name = _("History Entry")
36 verbose_name_plural = _("History Entries")
38 @classmethod
39 def log_field_changes(cls, instance, verb, fields=None):
40 """Log changes to fields to the ``field_changes`` field of the history record."""
41 if fields is None:
42 return
44 a = list()
45 for change in fields:
46 # Attempt to make text fields or long character fields look good.
47 if len(str(change.new_value)) > 128 or len(str(change.old_value)) > 128:
48 b = list()
49 diff = difflib.Differ()
50 for i in diff.compare(str(change.old_value).splitlines(), str(change.new_value).splitlines()):
51 b.append(i.strip())
53 a.append(" ".join(b))
54 else:
55 a.append(str(change))
57 instance.field_changes = "\n\n".join(a)
58 instance.save(update_fields=["field_changes"])