Do not monitor changes for field in django-simple-history
I am trying to monitor and display historical changes of my model. Problem is that every time user logins it saves it to historical model. I have tried to exclude this field like shown bellow, but it just saves new instance without field last_login.
Model:
class CustomUser(AbstractBaseUser, PermissionsMixin):
...
history = HistoricalRecords(excluded_fields=['last_login'])
View:
def user_history(request, pk):
user = get_object_or_404(CustomUser, pk=pk)
history_records = user.history.all().order_by("-history_date")
table = UserHistoryTable(history_records)
return render(request, "history.html", {
"name": user.username,
"instance": user,
"table": table,
})
Table:
class UserHistoryTable(tables.Table):
history_date = tables.DateTimeColumn(verbose_name="Date", format="d.m.Y H:i")
history_user = tables.Column(verbose_name="Modified By")
history_type = tables.Column(verbose_name="Change Type", accessor="get_history_type_display")
changes = tables.Column(empty_values=(), verbose_name="Changes")
class Meta:
model = CustomUser.history.model
attrs = {"class": "table table-striped table-hover table-bordered shadow-sm"}
template_name = "django_tables2/bootstrap4.html"
fields = ("history_date", "history_user", "history_type")
def render_changes(self, record):
if record.prev_record:
changes = []
for field in record.instance._meta.fields:
field_name = field.name
old_value = getattr(record.prev_record, field_name, None)
new_value = getattr(record, field_name, None)
if field_name == "password" and old_value != new_value:
changes.append(f"<strong>{field.verbose_name}:</strong> {'*' * 7} → {'*' * 7}")
elif old_value != new_value:
changes.append(f"<strong>{field.verbose_name}:</strong> {old_value} → {new_value}")
if changes:
return format_html("<br>".join(changes))
else:
return "No changes"
return "No previous record"
I need to display table with changes without empty entries
My current solution was to filter table in view, but I believe that is not the best solution and unnecesary data still remains in my database.
Model:
class CustomUser(AbstractBaseUser, PermissionsMixin):
...
history = HistoricalRecords()
View:
def user_history(request, pk):
user = get_object_or_404(CustomUser, pk=pk)
history_records = user.history.all().order_by("-history_date")
filtered_history_records = []
table = UserHistoryTable(history_records)
for record in history_records:
changes = table.render_changes(record)
if 'last login' not in changes:
filtered_history_records.append(record)
filtered_table = UserHistoryTable(filtered_history_records)
return render(request, "history.html", {
"name": user.username,
"instance": user,
"table": filtered_table,
})