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).
views:
100answers:
3
+2
Q:
How to implement Django model audit trail? How do you access logged in user in models save() method?
A:
Django models do not (on purpose) have access to the request
object. You must pass it to the model in a view.
Ignacio Vazquez-Abrams
2010-01-05 16:10:14
+1
A:
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).
Dominic Rodger
2010-01-05 16:10:29
Django-revision is more for tracking the status of a model as it evolves, doesn't seem to help with tracking the last user to modify the record.
MikeN
2010-01-05 18:38:44
Yes it does - see the "Version meta data" section of http://code.google.com/p/django-reversion/wiki/LowLevelAPI
Dominic Rodger
2010-01-06 06:38:28
A:
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.
Will Hardy
2010-01-05 16:44:02