Get current user log in signal in Django

Djanux picture Djanux · Jan 18, 2011 · Viewed 10.5k times · Source

I am just using the admin site in Django. I have 2 Django signals (pre_save and post_save). I would like to have the username of the current user. How would I do that? It does not seem I can send a request Or I did not understand it.

Thanks

Answer

Greg Ball picture Greg Ball · Jan 16, 2012

Being reluctant to mess around with thread-local state, I decided to try a different approach. As far as I can tell, the post_save and pre_save signal handlers are called synchronously in the thread that calls save(). If we are in the normal request handling loop, then we can just walk up the stack to find the request object as a local variable somewhere. e.g.

from django.db.models.signals import pre_save
from django.dispatch import receiver

@receiver(pre_save)
def my_callback(sender, **kwargs):
    import inspect
    for frame_record in inspect.stack():
        if frame_record[3]=='get_response':
            request = frame_record[0].f_locals['request']
            break
    else:
        request = None
    ...

If there's a current request, you can grab the user attribute from it.

Note: like it says in the inspect module docs,

This function relies on Python stack frame support in the interpreter, which isn’t guaranteed to exist in all implementations of Python.