Wednesday, June 1, 2011

Re: Auditing Record Changes in All Admin Tables

The model code still needs to stay in the model, it is just the save_model method had to be moved to the admin.py.  I think the following is what you are looking for:

models.py
---------------
from django.db import models
from django.contrib.auth.models import User

class AuditedTable(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    created_by = models.ForeignKey(User, editable=False)
    updated = models.DateTimeField(auto_now=True)
    updated_by = models.ForeignKey(User, editable=False)
   
    class Meta:
        abstract = True

class Entity1(AuditedTable):
    title = models.CharField(max_length=20)
   
    def __unicode__(self):
        return self.title

admin.py
-------------
from django.contrib import admin
from app.models import Entity1

class AuditAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        if change:
            obj.updated_by = request.user
        else:
            obj.created_by = request.user
        obj.save()

class Entity1Admin(AuditAdmin):
    pass

admin.site.register(Entity1, Entity1Admin)

Hope that helps,

Ryan

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/django-users/-/NV9uTUJxUVRkTW9K.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment