Get current user log in signal in Django

后端 未结 6 2090
忘掉有多难
忘掉有多难 2021-02-05 10:01

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 n

6条回答
  •  感动是毒
    2021-02-05 10:22

    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.

提交回复
热议问题