Track model object changes over time so that you know who done what.
-
Install the package
- For Django<4.0
pip install 'django-model-tracker jsonfield'
- For Django>=4.0
pip install 'django-model-tracker'
- For Django<4.0
-
Add Application to your project's INSTALLED_APPs
INSTALLED_APPS = (
'....',
'ModelTracker',
)
- Add the following line to your urls.py
import ModelTracker
urlpatterns = patterns('',
...
url(r'^track/', include('ModelTracker.urls')),
...
)
- Run Migrations
python manage.py migrate ModelTracker
- Add the following line to your models.py file
from ModelTracker import Tracker
- Convert each Model you want to track to inhert from
Tracker.ModelTracker
instead ofmodels.Model
Old Code
class Employee(models.Model):
name=models.CharField(max_length=255)
address=models.CharField(max_length=255)
age=models.IntegerField()
New Code
class Employee(Tracker.ModelTracker):
name=models.CharField(max_length=255)
address=models.CharField(max_length=255)
age=models.IntegerField()
- For each save() call, add the user the username
- Old Code
emp=Employee()
emp.save()
* New Code
emp=Employee()
emp.save(request.user.username)
-
Starting from version of 0.5, you can pass a event_name parameter to mark change as an event
- New Code
emp=Employee()
emp.save(request.user.username,event_name="Created the user")
You can add ModelTracker.middleware.ModelTrackerMiddleware
to your Middleware classes to get the username automatically from the request.
MIDDLEWARE_CLASSES = (
'....',
'ModelTracker.middleware.ModelTrackerMiddleware',
)
Note: If you pass username as None
then the change won't be saved.
There are 3 ways to see the history of a record
- go to
ModelTracker
url and selectTable
and enterid
. - call
showModelChanges
by POST and sendcsrftokenmiddleware
to return history as html. - call
getModelChanges
which returns history as Json.
There is 2 ways to update an object by django admin
- Handle save and delete in ModelAdmin as follows
def save_model(self, request, obj, form, change): obj.save(request.user.username,"Editing From admin interface") def delete_model(self, request, obj): obj.delete(username=request.user.username, event_name="Deleting From admin interface")
- Inhert from TrackerAdmin rather ModelAdmin
from ModelTracker.Tracker import TrackerAdmin admin.site.register(employee, TrackerAdmin)