Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current user log in signal in Django

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

like image 772
Djanux Avatar asked Jan 18 '11 08:01

Djanux


3 Answers

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.

like image 91
Greg Ball Avatar answered Nov 05 '22 14:11

Greg Ball


If you are using the admin site why not use a custom model admin

class MyModelAdmin( admin.ModelAdmin ):
    def save_model( self, request, obj, form, change ):
        #pre save stuff here
        obj.save()
        #post save stuff here



admin.site.register( MyModel, MyModelAdmin )

A signal is something that is fired every time the object is saved regardless of if it is being done by the admin or some process that isn't tied to a request and isn't really an appropriate place to be doing request based actions

like image 35
Dave LeBlanc Avatar answered Nov 05 '22 14:11

Dave LeBlanc


You can use a middleware to store the current user: http://djangosnippets.org/snippets/2179/

Then you would be able to get the user with get_current_user()

like image 3
jbochi Avatar answered Nov 05 '22 12:11

jbochi