djangodjango-simple-history

django simple history doesn't show in admin


I have followed the Django-simple-history documentation to display history from the admin page but somehow the history doesn't seem to appear from the admin page. I am using Django version 3.1.2

Here is my admin

from django.contrib import admin
from simple_history.admin import SimpleHistoryAdmin
from .models import Company

admin.site.register(Company, SimpleHistoryAdmin)

Solution

  • You can try this way:

    Suppose you have only one field in your Company model i.e name field so the model will look as follows:

    models.py

    from django.db import models
    
    class Company(models.Model):
        name = models.CharField(max_length=200)
    

    Now import the HistoricalRecords class from simple_history.models and add the history field in the Company model.

    from django.db import models
    from simple_history.models import HistoricalRecords
    
    class Company(models.Model):
        name = models.CharField(max_length=200)
        history = HistoricalRecords()
    
        def __str__(self):
            return self.name
    

    Now create a class named CompanyHistoryAdmin in admin.py by inheriting the SimpleHistoryAdmin class after importing it from simple_history.admin. see below code:

    admin.py

    from django.contrib import admin
    from simple_history.admin import SimpleHistoryAdmin
    from .models import Company
    
    # Register your models here.
    class CompanyHistoryAdmin(SimpleHistoryAdmin):
        list_display = ['id', 'name']
        history_list_display = ['status']
        search_fields = ['name']
    
    admin.site.register(Post, CompanyHistoryAdmin)
    

    The list_display list will display the records in the form of rows and two columns i.e id & name in the admin section. using search_fields you can search the records in admin section by the name or any other field you provide. And history_list_display will show the status of any record that you want to see. To see the history of the record click on any record and then click the history button on the right handside top corner.

    More information read the docs.