aroooo
aroooo

Reputation: 5086

Proper way to log Django User activity

What's the proper way to log user activity in Django?

For example let's say a user has Groups, and I'd like to keep a record of when Object1 has been added or removed.

The method that comes to mind is to create a new record every time and pull the latest record but this feels wrong (and causes some filtering problems, eg: you can't just filter on is_member=True since you'll get stale results). Is there a proper way to log these in Django?

Upvotes: 3

Views: 3435

Answers (3)

Louis Barranqueiro
Louis Barranqueiro

Reputation: 10238

To log something like that I recommend you to create an core app with a TimeStampModel model:

from django.db import models
from django.utils.timezone import now

class TimeStampModel(models.Model):
    """
    TimeStampModel class allows us to follow creation and update of each inherit instance
    """
    created_at = models.DateTimeField(auto_now_add=now(), editable=False)
    updated_at = models.DateTimeField(auto_now=now(), editable=False)

    class Meta:
        abstract = True

Now, inherit each models from TimeStampModel that you want to record creation or update date.

E.g:

from django.db import models
from core.models import TimeStampModel

class Token(TimeStampModel):
    uuid = models.CharField(max_length=255, primary_key=True)
    # ...

You can also add a delete attribute (Boolean) to realize logical delete. And the last update, will be the date of deletion.

Two Scoops of Django 1.8 recommends also this practice.

Upvotes: 0

Ward
Ward

Reputation: 2862

You can use django-auditable-models for that. It will hook in the django workflow, and will avoid that you have to write all logic yourself.

Upvotes: 3

Related Questions