Using django-auditlog, how can I display the 'actor_id' for a particular model?

Question:

I have created a simple Django application to display individual articles. These articles have a number of fields that users can edit. I am using the package ‘django-auditlog’ to log changes to these article models. So far, I have simply followed the auditlog installation doc to setup model history tracking (as well as enabling the middleware to allow ‘actor_id’ to be tracked). I have also added the example code that displays the most recent changes on the individual model pages as such:

<!-- History display -->
<div class="table-responsive">
  <table id="history" class="table table-striped table-bordered">
    <thead>
      <tr>
        <th>Actor</th>
        <th>Field</th>
        <th>From</th>
        <th>To</th>
      </tr>
    </thead>
    <tbody>
    <!-- Human readable - change to '.changes_dict.' for proper logs -->
    {% for key, value in article.history.latest.changes_display_dict.items %}
      <tr>
        <td>{{ article.history.latest.author_id }}</td>
        <td>{{ key }}</td>
        <td>{{ value.0|default:"None"|striptags|safe }}</td>
        <td>{{ value.1|default:"None"|striptags|safe }}</td>
      </tr>
    {% empty %}
      <p>No history for this item has been logged yet.</p>
    {% endfor %}
    </tbody>
  </table>
</div>

As my code may suggest, I am trying to add an additional column to the history table to show who made the changes that are being displayed.

Is there an easy way to do this through auditlog, or will I have to create some kind of sql query to my sqlite auditlog db table to retrieve the ‘author_id’ field?

Thank you!

Asked By: JasonPB

||

Answers:

I figured out the answer after looking through the models file for Django AuditLog. It is not possible to pull the actor out directly from the history field of the model if you have created the history field using the AuditlogHistoryField() method as described in the django-auditlog tutorial.

Instead, I did the following:

In the views.py file

from auditlog.models import LogEntry
...
dal_log = LogEntry.objects.get_for_object(article)
...
context = {'article': article, 'logs': dal_log}
return render(request, "detail.html", context)

Then in my template, I was able to work with the log entries for the specified object (in my case, these were ‘article’ models). There may be a cleaner way, but this worked for me.

Answered By: JasonPB

Try this (in my version, I have actor_id instead of author_id) :

<td>{{ article.history.latest.get_action_display }}</td>
<td>{{ article.history.latest.actor.username }}</td>
<td>{{ key }}</td>
<td>{{ value.0|default:"None" }}</td>
<td>{{ value.1|default:"None" }}</td>
Answered By: Rat619
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.