Reputation: 143
How do I log which user has performed what changes(field value) in any of model?
The way I tried:
Write code in the pre_save signal. In that, I am getting the old and new value, but request object(for current login user) and list of updated fields are not getting.
Write code in Django Forms save(), but same issue can fetch request object(current login user).
Upvotes: 1
Views: 1644
Reputation: 8202
You might also consider django-dirtyfields
This lets you obtain a dict of field values that have been altered since the model was instantiated. You could subclass the model save
method, and write the current user and the altered fields to a logfile or save a logging model. It would also allow you to decide that a subset of possible fields or changes thereto are worthy of being logged, and ignore other changes.
Upvotes: 0
Reputation: 476659
You might consider using django-simply-history
[readthedocs]. You can add this app to the INSTALLED_APPS
and in the MIDDLEWARE
:
# settings.py
INSTALLED_APPS = [
# ...
'simple_history',
# ...
]
MIDDLEWARE = [
# ...
'simple_history.middleware.HistoryRequestMiddleware',
# ...
]
The middleware is then used to track the user that triggered a view which resulted in changes to models "with a history".
You can add a history manager to a model like:
from django.db import models
from simple_history.models import HistoricalRecords
class SomeModel(models.Model):
some_field = models.CharField(max_length=128)
history = HistoricalRecords()
It will add copies of the SomeModel
with a timestamp and a reference to the user that made the change in an extra table.
See the User tracking section [readthedocs] for more info.
Upvotes: 3