[Django]-Django: How to create a user action log/trace with vizualization

1👍

There are many ways to achieve that. Try reading this link first. Also, you can use LogEntry for tracking the creation, deletion, or changes of the models you have. Also, it shows you the information you need in the admin panel, or also you can use some other third-party packages.
Or you may want to create your own Model to create logs for your application and this link may help you, but do not reinvent the wheel and analyze your situation.

from django.contrib.admin.models import LogEntry, ADDITION

LogEntry.objects.log_action(
    user_id=request.user.pk,
    content_type_id=get_content_type_for_model(object).pk,
    object_id=object.pk,
    object_repr=force_text(object),
    action_flag=ADDITION
)
👤Shayan

1👍

  1. Create a model to store the user actions. OP will want the Action model to have at least two fields – user (FK to the user model) and action (user action).

    from django.db import models
    
    class Action(models.Model):
        user = models.ForeignKey(User, on_delete=models.CASCADE)
        action = models.CharField(max_length=255)
    
  2. Create a way to store the user actions.

    def store_user_action(user, action):
        action = Action(user=user, action=action)
        action.save()
    
  3. Then if one wants to store when the user changed password, one will go to the view that deals with the change password and call our method store_user_action(request.user, 'changed password') when successful.

  4. To then visualise the user actions, OP can see the records in the Django Admin, create views and templates, … There are different possibilities.

Leave a comment