pythondjangodjango-simple-history

How to get the user that modified an object? django-simple-history


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,


Solution

  • 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.