django-model-audit-history
Provides an AuditHistory
model field to store a chronological record of changes to a model (“audit history”) on the model. The historical record is stored in a designated JSON field, so no additional database tables are required.
Supports Django 1.11 (and possibly Django 2.x in the future) and PostgreSQL database backends.
CI
Usage
The basic principles are as follows:
-
To enable this for a model, you have to make these changes:
- add an
AuditHistoryField
namedhistory
to the model - add the
AuditHistoryMixin
to the model class - create ModelAdmin:
ModelAdmin(AuditHistoryAdminMixin, admin.ModelAdmin): pass
- add your ModelAdmin to admin site
admin.site.register(model, ModelAdmin)
- add an
-
Then, instead of calling regular
save()
on the model after changing it, callsave_with_audit_record()
instead (passing in some meta data you want saved alongside, e.g. theevent
that caused the change, theuser
triggering it and somepayload
usually the set of modified fields. -
The history will appear in human-readable form in the admin.
That’s pretty much all there is to it.
Testapp setup and first steps
- Install Postgres locally (e.g. 10.x)
- Create local database
audithistory
, owned by userdev
- Create a virtualenv and activate:
virtualenv venv
, thensource venv/bin/activate
- Install dependencies into virtualenv:
pip install --requirement requirements.txt
- Run
manage.py migrate
- Run
manage.py createsuperuser
- Run
manage.py runserver
- Create new model on http://localhost:8000/admin/test_app/blogpost/
- Edit model via http://localhost:8000/edit/1/
- Reload admin page and inspect history record
Run tests in local environment:
- Run
manage.py test
(Ensure that user dev has rights to db creationalter user dev createdb;
)