Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tying in to Django Admin's Model History

The Setup:

  • I'm working on a Django application which allows users to create an object in the database and then go back and edit it as much as they desire.
  • Django's admin site keeps a history of the changes made to objects through the admin site.

The Question:

  • How do I hook my application in to the admin site's change history so that I can see the history of changes users make to their "content"?
like image 253
akdom Avatar asked Jun 12 '09 16:06

akdom


People also ask

What is Django reversion?

django-reversion is an extension to the Django web framework that provides version control for model instances.

How do I automatically register all models in Django admin?

To automate this process, we can programmatically fetch all the models in the project and register them with the admin interface. Open admin.py file and add this code to it. This will fetch all the models in all apps and registers them with the admin interface.

How do I restrict access to admin pages in Django?

Django admin allows access to users marked as is_staff=True . To disable a user from being able to access the admin, you should set is_staff=False . This holds true even if the user is a superuser. is_superuser=True .


1 Answers

The admin history is just an app like any other Django app, with the exception being special placement on the admin site.

The model is in django.contrib.admin.models.LogEntry.

When a user makes a change, add to the log like this (stolen shamelessly from contrib/admin/options.py:

from django.utils.encoding import force_unicode from django.contrib.contenttypes.models import ContentType from django.contrib.admin.models import LogEntry, ADDITION LogEntry.objects.log_action(     user_id         = request.user.pk,      content_type_id = ContentType.objects.get_for_model(object).pk,     object_id       = object.pk,     object_repr     = force_unicode(object),      action_flag     = ADDITION ) 

where object is the object that was changed of course.

Now I see Daniel's answer and agree with him, it is pretty limited.

In my opinion a stronger approach is to use the code from Marty Alchin in his book Pro Django (see Keeping Historical Records starting at page 263). There is an application django-simple-history which implements and extends this approach (docs here).

like image 128
Van Gale Avatar answered Sep 21 '22 14:09

Van Gale