django-audit-fields

pypi clinicedc

Source code: https://github.com/erikvw/django-audit-fields


This module has two model mixins that when used with a Django model adds a group of audit fields updated when a model instance is created and modified. This is one part of a strategy to be compliant with guidelines such as Good Clinical Practice (GCP), 21 CFR part 11, EU GDPR, UK GDPR, and the South African POPI Act. See the full list below of fields below.

This module includes django-revision, which tracks the source code revision, and is best used together with django-simple-history.

As of version 1.1.0, edc-utils is no longer a dependency of django-audit-fields.

Documentation: django-audit-fields.readthedocs.io

Requirements: DJ5.2+, py3.12+

Older versions

  • <=0.3.3 (DJ 3.1, py 3.7, 3.8)

  • >=0.3.4 (DJ 3.2+, py 3.9+)

  • >=0.3.14 (DJ4.2, py3.11) includes locale

Installation

pip install django-audit-fields

Add django-audit-fields to INSTALLED_APPS

INSTALLED_APPS = [
    "...",
    "django_audit_fields.apps.AppConfig",
    "..."]

Usage

Add model fields to track creation and modification dates, users and more on save.

Declare your model using AuditModelMixin

from django_audit_fields.models import AuditModelMixin
from simple_history.models import HistoricalRecords

class MyModel(AuditModelMixin,  models.Model):

    history = HistoricalRecord()

    class Meta(AuditModelMixin.Meta):
        pass

Preferably, use a UUID as primary key by declaring your model using AuditUuidModelMixin

from django_audit_fields.models import AuditUuidModelMixin
from simple_history.models import HistoricalRecords

class MyModel(AuditUuidModelMixin, models.Model):

    history = HistoricalRecord()

    class Meta(AuditUuidModelMixin.Meta):
        pass

Model mixins AuditModelMixin and AuditUuidModelMixin

The model mixin AuditUuidModelMixin sets the id fields to a UUIDField instead of an integer field.

Model mixins AuditModelMixin and AuditUuidModelMixin add audit fields:

Field

Field class

Update event

created

DateTimeField

only set on pre-save add

modified

DateTimeField

updates on every save

user_created

CharField

only set on pre-save add

user_modified

CharField

updates on every save

hostname_created

CharField

only set on pre-save add

hostname_modified

CharField

updates on every save

locale_created

CharField

only set on pre-save add

locale_modified

CharField

updates on every save

revision

RevisionField*

updates on every save