In Django, how to send a post-login message to the user?

后端 未结 2 958
囚心锁ツ
囚心锁ツ 2021-01-24 15:08

I have a Django site in which I show a success message to the user when they\'ve logged in. I do this with a signal like this:

def post_login_actions(sender, use         


        
2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-24 15:44

    In normal circumstances, the AuthenticationMiddleware will set the user as an attribute on the request object:

    request.user = SimpleLazyObject(lambda: get_user(request))
    

    When you add a message, Django will first check whether that attribute has been set:

    if hasattr(request, 'user') and request.user.is_authenticated():
        return request.user.message_set.create(message=message)
    

    But now you're running tests and the login method of Client creates a request object from scratch without the user attribute.

    So you've got two options: patching Django or making your signal receiver work in this case by changing it to this:

    def post_login_actions(sender, user, request, **kwargs):
        if not hasattr(request, 'user'):
            setattr(request, 'user', user)
        messages.success(request, "Hello There. You're now logged in.")
    

提交回复
热议问题