djangodjango-modelsdjango-viewsdjango-templatesdjango-simple-history

Django-simple-history to display logs on webpage other than admin website


I have been successful to register Django-simple-history with admin page. I have now been trying to get audit (CRUD) logs to display on a webpage other than the admin site. The page currently displays blank.

Here is my attempt to get this working -

views.py file

def audit_trail(request, id):
    if request.method == "GET":
        obj = My_Model.history.all(pk=id)
        return render(request, 'audit_trail.html', context={'object': obj})

audit_trail.html file


{%extends "did/base.html" %}

{% block content %}

{% for h in object%}
   {{ h.id }}
   {{ h.carrier }}
{% endfor %}

{% endblock content %}

url pattern

path('audit_trail/', views.audit_trail, name='audit_page'),

** Model File **

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from simple_history.models import HistoricalRecords

class My_Model(models.Model):
    field1 = models.CharField(max_length=100)
    field2 = models.DateTimeField(default=timezone.now)
    field3 = models.CharField(max_length=100)
    history = HistoricalRecords()

Solution

  • The issue here is that your queryset isn't returning anything. The primary key on the historical table is history_id rather than id from your base My_Model table. Thus, if you update your query to be My_Model.history.filter(id=id), this should then work.