Mohamed M El-Kalioby
Posted on March 13, 2021
First, the credit of the cover photo is for https://matomo.org/
When working in mission-critical applications, it is critical to know when and how an object (DB row) got here.
For that, we created django-model-tracker a Django application that handle tracking Django Models changes with the username of the user who did the change, then the admin team can view the changes and restore the object to an older state.
Installation
- Install the package from pip
pip install django-model-tracker
-
In the
settings.py
add ModelTracker to INSTALLED_APPS.
INSTALLED_APPS = ( '....', 'ModelTracker', '....' )
Run the migrations for the application
python manage.py migrate ModelTracker
Tracking your models
To track a model, you need to change the inheritance from models.Model
to ModelTracker.Tracker
e.g
from ModelTracker import Tracker
class Employee(Tracker.ModelTracker):
name=models.CharField(max_length=255)
....
When you save an Employee object, you can pass the username as follows
emp=Employee()
emp.save(request.user.username)
Notes:
- If you don't pass a username, ModelTracker will check pick the username from a ModelTracker middleware
(ModelTracker.middleware.ModelTrackerMiddleware)
- You can pass username as
None
to skip saving the tracking info. - The username is a string so you can give names for the management commands as you like.
- There is second optional parameter which
event_name
which can be used a tag the change.
This is a quick tour for django-model-tracker
, you can find more information on the GitHub Repo
Posted on March 13, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
October 18, 2024
October 7, 2024