Internals

You might be interested in the way things work on the inside of Auditlog. This section covers the internal APIs of Auditlog which is very useful when you are looking for more advanced ways to use the application or if you like to contribute to the project.

The documentation below is automatically generated from the source code.

Models and fields

class auditlog.models.LogEntry(*args, **kwargs)[source]

Represents an entry in the audit log. The content type is saved along with the textual and numeric (if available) primary key, as well as the textual representation of the object when it was saved. It holds the action performed and the fields that were changed in the transaction.

If AuditlogMiddleware is used, the actor will be set automatically. Keep in mind that editing / re-saving LogEntry instances may set the actor to a wrong value - editing LogEntry instances is not recommended (and it should not be necessary).

class Action[source]

The actions that Auditlog distinguishes: creating, updating and deleting objects. Viewing objects is not logged. The values of the actions are numeric, a higher integer value means a more intrusive action. This may be useful in some cases when comparing actions because the __lt, __lte, __gt, __gte lookup filters can be used in queries.

The valid actions are Action.CREATE, Action.UPDATE and Action.DELETE.

exception DoesNotExist
exception MultipleObjectsReturned
changes_dict
Returns:The changes recorded in this log entry as a dictionary object.
changes_display_dict
Returns:The changes recorded in this log entry intended for display to users as a dictionary object.
changes_str

Return the changes recorded in this log entry as a string. The formatting of the string can be customized by setting alternate values for colon, arrow and separator. If the formatting is still not satisfying, please use LogEntry.changes_dict() and format the string yourself.

Parameters:
  • colon – The string to place between the field name and the values.
  • arrow – The string to place between each old and new value.
  • separator – The string to place between each field.
Returns:

A readable string of the changes in this log entry.

class auditlog.models.LogEntryManager[source]

Custom manager for the LogEntry model.

get_for_model(model)[source]

Get log entries for all objects of a specified type.

Parameters:model (class) – The model to get log entries for.
Returns:QuerySet of log entries for the given model.
Return type:QuerySet
get_for_object(instance)[source]

Get log entries for the specified model instance.

Parameters:instance (Model) – The model instance to get log entries for.
Returns:QuerySet of log entries for the given model instance.
Return type:QuerySet
get_for_objects(queryset)[source]

Get log entries for the objects in the specified queryset.

Parameters:queryset (QuerySet) – The queryset to get the log entries for.
Returns:The LogEntry objects for the objects in the given queryset.
Return type:QuerySet
log_create(instance, **kwargs)[source]

Helper method to create a new log entry. This method automatically populates some fields when no explicit value is given.

Parameters:
  • instance (Model) – The model instance to log a change for.
  • kwargs – Field overrides for the LogEntry object.
Returns:

The new log entry or None if there were no changes.

Return type:

LogEntry

class auditlog.models.AuditlogHistoryField(pk_indexable=True, delete_related=True, **kwargs)[source]

A subclass of py:class:django.contrib.contenttypes.fields.GenericRelation that sets some default variables. This makes it easier to access Auditlog’s log entries, for example in templates.

By default this field will assume that your primary keys are numeric, simply because this is the most common case. However, if you have a non-integer primary key, you can simply pass pk_indexable=False to the constructor, and Auditlog will fall back to using a non-indexed text based field for this model.

Using this field will not automatically register the model for automatic logging. This is done so you can be more flexible with how you use this field.

Parameters:
  • pk_indexable (bool) – Whether the primary key for this model is not an int or long.
  • delete_related (bool) – By default, including a generic relation into a model will cause all related objects to be cascade-deleted when the parent object is deleted. Passing False to this overrides this behavior, retaining the full auditlog history for the object. Defaults to True, because that’s Django’s default behavior.

Return all objects related to objs via this GenericRelation.

Middleware

class auditlog.middleware.AuditlogMiddleware(get_response=None)[source]

Middleware to couple the request’s user to log items. This is accomplished by currying the signal receiver with the user from the request (or None if the user is not authenticated).

process_exception(request, exception)[source]

Disconnects the signal receiver to prevent it from staying active in case of an exception.

process_request(request)[source]

Gets the current user from the request and prepares and connects a signal receiver with the user already attached to it.

process_response(request, response)[source]

Disconnects the signal receiver to prevent it from staying active.

static set_actor(user, sender, instance, signal_duid, **kwargs)[source]

Signal receiver with an extra, required ‘user’ kwarg. This method becomes a real (valid) signal receiver when it is curried with the actor.

Signal receivers

auditlog.receivers.log_create(sender, instance, created, **kwargs)[source]

Signal receiver that creates a log entry when a model instance is first saved to the database.

Direct use is discouraged, connect your model through auditlog.registry.register() instead.

auditlog.receivers.log_delete(sender, instance, **kwargs)[source]

Signal receiver that creates a log entry when a model instance is deleted from the database.

Direct use is discouraged, connect your model through auditlog.registry.register() instead.

auditlog.receivers.log_update(sender, instance, **kwargs)[source]

Signal receiver that creates a log entry when a model instance is changed and saved to the database.

Direct use is discouraged, connect your model through auditlog.registry.register() instead.

Calculating changes

auditlog.diff.get_field_value(obj, field)[source]

Gets the value of a given model instance field.

Parameters:
  • obj (Model) – The model instance.
  • field (Any) – The field you want to find the value of.
Returns:

The value of the field as a string.

Return type:

str

auditlog.diff.get_fields_in_model(instance)[source]

Returns the list of fields in the given model instance. Checks whether to use the official _meta API or use the raw data. This method excludes many to many fields.

Parameters:instance (Model) – The model instance to get the fields for
Returns:The list of fields for the given model (instance)
Return type:list
auditlog.diff.model_instance_diff(old, new)[source]

Calculates the differences between two model instances. One of the instances may be None (i.e., a newly created model or deleted model). This will cause all fields with a value to have changed (from None).

Parameters:
  • old (Model) – The old state of the model instance.
  • new (Model) – The new state of the model instance.
Returns:

A dictionary with the names of the changed fields as keys and a two tuple of the old and new field values as value.

Return type:

dict

auditlog.diff.track_field(field)[source]

Returns whether the given field should be tracked by Auditlog.

Untracked fields are many-to-many relations and relations to the Auditlog LogEntry model.

Parameters:field (Field) – The field to check.
Returns:Whether the given field should be tracked.
Return type:bool

Registry

class auditlog.registry.AuditlogModelRegistry(create: bool = True, update: bool = True, delete: bool = True, custom: Optional[Dict[django.db.models.signals.ModelSignal, Callable]] = None)[source]

A registry that keeps track of the models that use Auditlog to track changes.

contains(model: django.db.models.base.ModelBase) → bool[source]

Check if a model is registered with auditlog.

Parameters:model – The model to check.
Returns:Whether the model has been registered.
Return type:bool
register(model: django.db.models.base.ModelBase = None, include_fields: Optional[List[str]] = None, exclude_fields: Optional[List[str]] = None, mapping_fields: Optional[Dict[str, str]] = None)[source]

Register a model with auditlog. Auditlog will then track mutations on this model’s instances.

Parameters:
  • model – The model to register.
  • include_fields – The fields to include. Implicitly excludes all other fields.
  • exclude_fields – The fields to exclude. Overrides the fields to include.
  • mapping_fields – Mapping from field names to strings in diff.
unregister(model: django.db.models.base.ModelBase) → None[source]

Unregister a model with auditlog. This will not affect the database.

Parameters:model – The model to unregister.