2

I am trying to save the history of an object by using django-simply-history library, so far i can see the changes of the object itself but not the user that made the changes.

I have the following set up.

Settings:

# settings.py

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

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

Models:

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()

Then in the Shell i do:

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

Thanks,

Jorge
  • 105
  • 9

1 Answers1

4

The simple history middleware will store the user that made the change in the .history_user field of the history record. You thus can obtain the latest user that changed the Customer object with:

customer.history.all().last().history_user

Beware that you can only make changes with a user in the webserver, for example with a view, or with the ModelAdmin. If you make changes with the Django shell itself, there is no "active user", and in that case the user stored in the historical record will be NULL/None.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • customer.history.all().last().history_user In the shell won't print anything but still it does not give any error, I don't know why exactly. – Jorge Aug 24 '21 at 10:52
  • @Jorge: because if you alter objects in the shell, then there is *no* user, so the user is unknown, and `history_user` is set to `None` in that case. – Willem Van Onsem Aug 24 '21 at 10:58
  • @Jorge: you thus should make a change through the website, and then in the shell (or the webserver) you can inspect the user that made the latest change. – Willem Van Onsem Aug 24 '21 at 10:58
  • @Jorge: Django's shell is not attached to a Django user, so hence the middleware of simple history can not capture any user, not because they did not implement it, but because it makes no sense conceptually. – Willem Van Onsem Aug 24 '21 at 10:59
  • Ohhh alright, thank you very much !!!!!! then everything it is fine. – Jorge Aug 24 '21 at 11:39