【问题标题】:django simple history doesn't show in admindjango 简单历史不会显示在管理员中
【发布时间】:2020-11-23 18:44:28
【问题描述】:

我已按照Django-simple-history 文档从管理页面显示历史记录,但不知何故,管理页面似乎没有显示历史记录。我正在使用 Django 版本 3.1.2

这是我的管理员

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

admin.site.register(Company, SimpleHistoryAdmin)

【问题讨论】:

  • 设置中的已安装应用和简单历史中间件设置中间件中添加simple_history应用了吗?
  • 是的,我已经添加了
  • 可以分享Company型号代码吗?

标签: django django-simple-history


【解决方案1】:

你可以试试这个方法:

假设您的 Company 模型中只有一个字段,即 name 字段,那么模型将如下所示:

models.py

from django.db import models

class Company(models.Model):
    name = models.CharField(max_length=200)

现在从simple_history.models 导入HistoricalRecords 类,并在Company 模型中添加历史字段。

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

现在通过在从simple_history.admin 导入SimpleHistoryAdmin 类后继承SimpleHistoryAdmin 类,在admin.py 中创建一个名为CompanyHistoryAdmin 的类。见以下代码:

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)

list_display 列表将以行和两列的形式显示记录,即管理部分中的idname。 使用search_fields,您可以按名称或您提供的任何其他字段搜索管理部分中的记录。 history_list_display 将显示您想查看的任何记录的状态。 要查看记录的历史记录,请单击任何记录,然后单击右上角的历史记录按钮。

更多信息read the docs.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-04
    • 2016-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-01
    相关资源
    最近更新 更多