Overview of django-auditlog
masterdjango.contrib.admin log.repository·master·Indexed 23 days ago
https://github.com/jazzband/django-auditlogA lightweight, reusable Django app for tracking and logging changes to model instances. It records object changes and the associated actor using JSON summaries for efficient storage. Features include automatic actor tracking via middleware, support for masking sensitive fields, many-to-many field tracking, and correlation ID (CID) management. Includes management commands like auditlogflush for clearing logs and auditlogmigratejson for migrating legacy text logs to JSON format.
django.contrib.admin log.By default, Auditlog does not track many-to-many relationships. For versions older than 2.1.0, you can use the following workaround to track changes on the 'through' model of a relationship.
Warning: This is a workaround and may not be stable across releases. For versions 2.1.0 and onwards, use the official many-to-many fields section in the documentation.
To implement this:
auditlog.register(MyModel.related.through).LogEntry.objects.get_for_objects() and combining the QuerySets.# Register the through model
auditlog.register(MyModel.related.through)
# Retrieve combined history
obj = MyModel.objects.first()
rel_history = LogEntry.objects.get_for_objects(obj.related.all())
full_history = (obj.history.all() | rel_history.all()).order_by('-timestamp')To integrate Auditlog into your Django project, follow these two steps:
'auditlog' to your INSTALLED_APPS setting.python manage.py migrate to create or upgrade the required database tables.Optional: Automatic Actor Tracking
If you want Auditlog to automatically identify and set the 'actor' (the user performing the action) for log entries, you must also add the Auditlog middleware to your MIDDLEWARE setting.
To automatically capture the current user (the 'actor') and their IP address in audit logs, add auditlog.middleware.AuditlogMiddleware to your Django MIDDLEWARE setting.
It is recommended to place this middleware after any middleware that alters the request (e.g., authentication middleware).
MIDDLEWARE = (
# Request altering middleware, e.g., Django's default middleware classes
'auditlog.middleware.AuditlogMiddleware',
# Other middleware
)Version 3.0.0 changes how changes are stored, moving from json-text to json. To avoid long-running database migrations that cause downtime or synchronization issues with large datasets, use the two-step migration process:
Prepare settings: Before upgrading the package, add the following variables to your settings.py:
AUDITLOG_TWO_STEP_MIGRATION = TrueAUDITLOG_USE_TEXT_CHANGES_IF_JSON_IS_NOT_PRESENT = TrueUpgrade the package: Once upgraded, new records will be stored as JSON, while old records remain accessible via LogEntry.changes_text.
Run the migration command: Execute the auditlogmigratejson command to convert existing records to JSON format.
Cleanup: After the migration is complete, remove the two variables from settings.py or set them to False.
# settings.py
AUDITLOG_TWO_STEP_MIGRATION = True
AUDITLOG_USE_TEXT_CHANGES_IF_JSON_IS_NOT_PRESENT = TrueBy default, Auditlog only logs changes. To log when a model instance is accessed (e.g., viewed), you can use one of two methods:
auditlog.mixins.LogAccessMixin to your view class. The mixin requires the view to have a get_object method (standard for DetailView and UpdateView).accessed signal from auditlog.signals by passing the model class and the instance being accessed.# For Class-Based Views
from django.views.generic import DetailView
from auditlog.mixins import LogAccessMixin
class MyModelDetailView(LogAccessMixin, DetailView):
model = MyModel
# For Function-Based Views
from auditlog.signals import accessed
def profile_view(request, pk):
user = User.objects.get(pk=pk)
accessed.send(user.__class__, instance=user)
...If you are upgrading from a version prior to V3, you must review the official upgrade documentation to ensure a smooth transition.
Refer to the Upgrading to version 3 guide.
To automatically track changes to your Django models, use auditlog.register(). It is recommended to place this call at the bottom of your models.py file to ensure registration occurs whenever the model is imported. Auditlog ensures each model is only registered once to prevent duplicate entries.
from django.db import models
from auditlog.registry import auditlog
class MyModel(models.Model):
pass
auditlog.register(MyModel)Install the package using the Python Package Index (PyPI) by running the following command:
pip install django-auditlogYou can integrate audit logs directly into the Django Admin interface using AuditlogHistoryAdminMixin. This adds a "View" link to the admin changelist for each object, allowing users to see a paginated history of changes (user, timestamp, action, and field changes).
show_auditlog_history_link: Set to True to enable the "View" link in the changelist.auditlog_history_template: The template used to render the history page (default: auditlog/object_history.html).auditlog_history_per_page: The number of log entries to display per page (default: 10).from auditlog.mixins import AuditlogHistoryAdminMixin
@admin.register(MyModel)
class MyModelAdmin(AuditlogHistoryAdminMixin, admin.ModelAdmin):
show_auditlog_history_link = TrueYou can associate a correlation ID (cid) with log entries to track requests across services. This can be configured in Django settings using:
AUDITLOG_CID_HEADER: To read the CID from a specific request header.AUDITLOG_CID_GETTER: To use a custom function (getter) to retrieve the CID, which is useful for integrating with third-party packages like django-cid.Many-to-many (M2M) field changes are not tracked by default. To enable tracking, pass the field names as a set to the m2m_fields argument in register().
auditlog.register(MyModel, m2m_fields={"tags", "contacts"})