0

I need to have current user information in a model's save() overwrite for logging purposes.

I am writing a log entry when an instant saved. In that record I need to have current user as well. Saving can occur in a regular view, where I can have access to a request, however I cannot access to a request while in a admin session.

Am I missing something?

1 Answer 1

0

django-cuser to the rescue! This library adds middleware that can be called in a view, model method, etc to get the current user. It has much more functionality, but in essence you can access the current user in any model, modelAdmin, etc methods.

There are methods to access the user in modelAdmin instances, but instead of building up methods in both your views and custom admin instances, I'd stick w/ the save method.

Once set up, it can be called like this:

from cuser.middleware import CuserMiddleware

class SomeModel(models.Model):
    def save(self, *args, **kwargs):
        user = CuserMiddleware.get_user()
        # you can now access any attributes of the current user
        super(SomeModel,self).save(*args, **kwargs)
1
  • This is an interestingly simple and useful library. Thanks a lot for the pointer...
    – Can Baysal
    Feb 13, 2016 at 16:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.