Search code examples
djangoauthenticationadmin

How to access user information from Django model definition?


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?


Solution

  • 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)