Django Simple History: Don't want to track User

2 min read 05-10-2024
Django Simple History: Don't want to track User


Django Simple History: Don't Track User Changes

Problem: You're using Django Simple History to track changes in your models, but you don't want to record every user action, just the actual model changes. This might be because you're using a system where users aren't always logged in, or you simply don't need that level of granularity.

Rephrased: You want to keep track of the what changed in your database models, but not the who changed it.

Scenario: Imagine you're building a blog application. You want to track the content of each blog post when it's edited, but you don't necessarily care which user made the change.

Original Code:

from simple_history.models import HistoricalRecords

class BlogPost(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    history = HistoricalRecords()

The Solution:

Django Simple History provides a user field for each historical record by default. To disable tracking the user, simply set user_field to None:

from simple_history.models import HistoricalRecords

class BlogPost(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    history = HistoricalRecords(user_field=None)

Analysis:

By setting user_field to None, you effectively remove the user information from the historical records. This is useful in scenarios where:

  • Users aren't logged in: For applications where user login is not required, tracking user actions is irrelevant.
  • Focus on data: You're primarily interested in the model's changes, not who made them.
  • Privacy concerns: You want to avoid storing user data in historical records.

Example:

Let's say a user edits a blog post without logging in. Using the original code, the historical record would contain None for the user field. With user_field=None, the historical record will only store the updated title and content fields, without any mention of the user.

Further Considerations:

  • Custom User Field: If you want to track a custom field instead of the default user field, you can specify it using the user_field argument.
  • Anonymous Users: If you want to track actions by anonymous users, you can use the get_user_model() function to retrieve the user model and set user_field to the corresponding field.

Conclusion:

Django Simple History offers flexibility in controlling the information stored in historical records. By setting user_field to None, you can prioritize tracking model changes while excluding user information. This approach can be valuable for applications that prioritize data integrity or user privacy.

References: