Tying in to Django Admin's Model History

后端 未结 5 1098
小鲜肉
小鲜肉 2020-11-27 09:30

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
5条回答
  •  难免孤独
    2020-11-27 10:36

    Example Code

    Hello,

    I recently hacked in some logging to an "update" view for our server inventory database. I figured I would share my "example" code. The function which follows takes one of our "Server" objects, a list of things which have been changed, and an action_flag of either ADDITION or CHANGE. It simplifies things a wee bit where ADDITION means "added a new server." A more flexible approach would allow for adding an attribute to a server. Of course, it was sufficiently challenging to audit our existing functions to determine if a changes had actually taken place, so I am happy enough to log new attributes as a "change".

    from django.contrib.admin.models import LogEntry, User, ADDITION, CHANGE
    from django.contrib.contenttypes.models import ContentType
    
    def update_server_admin_log(server, updated_list, action_flag):
        """Log changes to Admin log."""
        if updated_list or action_flag == ADDITION:
            if action_flag == ADDITION:
                change_message = "Added server %s with hostname %s." % (server.serial, server.name)
            # http://dannyman.toldme.com/2010/06/30/python-list-comma-comma-and/
            elif len(updated_list) > 1:
                change_message = "Changed " + ", ".join(map(str, updated_list[:-1])) + " and " + updated_list[-1] + "."
            else:
                change_message = "Changed " + updated_list[0] + "."
            # http://stackoverflow.com/questions/987669/tying-in-to-django-admins-model-history
            try:
                LogEntry.objects.log_action(
                    # The "update" user added just for this purpose -- you probably want request.user.id
                    user_id = User.objects.get(username='update').id,
                    content_type_id = ContentType.objects.get_for_model(server).id,
                    object_id = server.id,
                    # HW serial number of our local "Server" object -- definitely change when adapting ;)
                    object_repr = server.serial,
                    change_message = change_message,
                    action_flag = action_flag,
                    )
            except:
                print "Failed to log action."
    

提交回复
热议问题