Get current user log in signal in Django

后端 未结 6 1764
忘掉有多难
忘掉有多难 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:35

    Without hack: use signals when user logs in / out to remember who is logged, and for the Django test framework, as long as you connect and it calls the signals, this will work too:

    current_user = None
    
    @receiver(user_logged_in, sender=User)
    def user_logged_in(sender, request, user, **kwargs):
        global current_user
        current_user = user
    
    @receiver(user_logged_out, sender=User)
    def user_logged_out(sender, request, user, **kwargs):
        global current_user
        current_user = None
    
    @receiver(post_save, sender=StatusHistory)
    def status_history_post_save(sender, instance: StatusHistory,
                                 created, **kwargs):
        global current_user
        if current_user is None or instance is None or instance.shipment is None:
            return
        # ok if we here -> user is connected, keep on:
        # .........
        # blabla
        # .........
    

提交回复
热议问题