How to do Django Audit

2

Good evening I am doing my App in Django and I am needing to create an audit log where I can register if they created / modified / deleted a record, which user did it and date of registration.

I'm grabbing suggestions to implement this functionality.

    
asked by jhon1946 11.07.2017 в 05:25
source

2 answers

3

There are several ways and it depends a lot on what your goal is and how you want to implement it:

  • Implement an abstract class for auditing:
      

    You can write an abstract class that has your audit fields, and the table will be created automatically with those fields, that is.

  • class AudtoriaMixin(models.Model):
        created_at = models.DateTimeField(auto_now_add=True)
        created_by = models.CharField(max_length=255, blank=True, editable=False)
        modified_at = models.DateTimeField(auto_now=True)
        modified_by = models.CharField(max_length=255, blank=True, editable=False)
    
        class Meta:
            abstract = True
    
    class Usuario(AudtoriaMixin):
        name = models.CharField(max_length=255)
    
  • Create a signal that captures the saved and deleted events and registers them in a table.
      

    The advantage of using this form is that it is not intrusive, you do not have to modify the models to use it, the disadvantage is that you can not customize some extra parameters, like the user you are modifying.

  • @receiver(post_save)
    def audit(sender, **kwargs):
        obj_str = str(kwargs.get('instance'))
        Auditoria(instancia = obj_str, accion="guardado").save()
    
  • Use a AuditTrail field:
      

    You can copy the snippet from link and use it to save an audit field for any model.

  • from django.db import models
    import audit
    
    class Usuario(models.Model):
        first_name = models.CharField(max_length=255)
        last_name = models.CharField(max_length=255)
        salary = models.PositiveIntegerField()
    
        history = audit.AuditTrail()
    
  • Use an external library to audit and save history:
      

    Finally you can use any of the applications that the django packages universe offers: link

  • answered by 11.07.2017 / 10:16
    source
    -1

    I have used simple history in a couple of projects and it has worked very well. It is responsible for creating a copy of the table or model on which you want to have a record.

    The installation is trivial and the creation of new tables only requires a line in models.py .

        
    answered by 11.07.2017 в 23:46