【问题标题】:How to get the user that modified an object? django-simple-history如何获取修改对象的用户? django-简单历史
【发布时间】:2021-08-24 10:38:17
【问题描述】:

我正在尝试使用 django-simply-history 库来保存对象的历史记录, 到目前为止,我可以看到对象本身的更改,但看不到进行更改的用户。

我有以下设置。

设置:

# settings.py

INSTALLED_APPS = [
    # ...
    'simple_history',
    # ...
]

MIDDLEWARE = [
    # ...
    'simple_history.middleware.HistoryRequestMiddleware',
    # ...
]

型号:

from django.db import models

from apps.companies.models import Company
from simple_history.models import HistoricalRecords

# Create your models here.
class Customer(models.Model):

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=20)
    dateCreated = models.DateTimeField(auto_now_add=True,)
    dateUpdated = models.DateTimeField(auto_now=True,)
    telephone = models.CharField(max_length=20, blank=True, null=True)
    address = models.CharField(max_length=20, blank=True, null=True)
    email = models.EmailField(max_length=254, blank=True, null=True)

    history = HistoricalRecords()

然后在 Shell 中我做:

customer = Customer.objects.all().last()

customer.name = "Test"

customer.save()

customer.history.all().last()

Out[79]: <HistoricalCustomer: Customer object (d2211cc1-9762-4f6d-9086-634deee95b1e) as of 2021-08-24 09:28:44.978543+00:00>

# How can I print the user that changed the object????
customer.history.all().last()_history_user

谢谢,

【问题讨论】:

    标签: python django django-simple-history


    【解决方案1】:

    简单的历史中间件会将做出更改的用户存储在历史记录的.history_user 字段中。因此,您可以获得更改Customer 对象的最新用户:

    customer.history.all().last()<strong>.history_user</strong>

    请注意,您只能通过网络服务器中的用户进行更改,例如使用视图或ModelAdmin。如果您使用 Django shell 本身进行更改,则没有“活动用户”,在这种情况下,历史记录中存储的用户将是 NULL/None

    【讨论】:

    • customer.history.all().last().history_user 在shell中不会打印任何东西但它仍然没有给出任何错误,我不知道究竟是为什么。
    • @Jorge:因为如果你在shell中修改对象,那么就没有没有用户,所以用户是未知的,history_user在里面设置为None那个案子。
    • @Jorge:因此,您应该通过网站进行更改,然后在 shell(或网络服务器)中检查进行最新更改的用户。
    • @Jorge:Django 的 shell 没有附加到 Django 用户,因此简单历史的中间件无法捕获任何用户,不是因为他们没有实现它,而是因为它在概念上没有意义。
    • 哦,好的,非常感谢!!!!!!那么一切都很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多