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

2👍

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.")
👤roam

0👍

I recommend instead of hacks mentioned by @roam, just add fail_silently=True argument to your messages calls – just to those ones that need to be run in the specific place like signals listeners (which you don’t want or can move them to a view).

messages.info(request, "some message", fail_silently=True)

This works as it does not raise MessageFailure exception. The tradeoff of not having this message displayed to user due to some other kind of error is not so big when we consider not having tests for that. And this method is fully supported in django – it is not any kind of hack that your teammate developer would think “WTF”?

👤thedk

Leave a comment