MikeN
MikeN

Reputation: 46287

How to implement Django model audit trail? How do you access logged in user in models save() method?

I want to keep track of the user who creates and then updates all of a given model's records. I have the "user" information in the logged in user's UserProfile (all users must be logged in to update these records).

Upvotes: 8

Views: 4468

Answers (4)

cyberspider789
cyberspider789

Reputation: 391

I find django-simple-history very easy to use. Importantly, it has a customisation available for tracking reason of change which can be strategically used to get input from users for knowing the reason.

Upvotes: 0

Dominic Rodger
Dominic Rodger

Reputation: 99771

It sounds like you're looking for django-reversion, which allows you to keep track of all changes to a given model, including some meta data about the change (e.g. who made it).

Upvotes: 3

Will Hardy
Will Hardy

Reputation: 14836

The quickest way to set the user field automatically for all changes made in the admin, would be by overriding the save_model method in your admin class (from the Django docs):

class ArticleAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        obj.user = request.user
        obj.save()

Otherwise, you can use something like django-revision mentioned by Dominic Rodger.

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798686

Django models do not (on purpose) have access to the request object. You must pass it to the model in a view.

Upvotes: 1

Related Questions