django simple history doesn't show in admin

牧云@^-^@ 提交于 2021-02-11 14:17:20

问题


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)

回答1:


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.



来源:https://stackoverflow.com/questions/64974458/django-simple-history-doesnt-show-in-admin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!