0

I want to execute one or more functions after a user logs into my site. How is this possible? I looked into Middleware. Djangobook says that I'll need this to run a piece of code on each and every request that Django handles. However, I just need the code run when the authentication happens successfully.

Note: I am using Django Allauth for authentication and I don't have any view of my own to log in users.

e4c5
  • 52,766
  • 11
  • 101
  • 134
MiniGunnR
  • 5,590
  • 8
  • 42
  • 66

2 Answers2

6

You need to tap into Allauth's signals. Specifically the user logged in signal

allauth.account.signals.user_logged_in(request, user)

Sent when a user logs in.

So add code similar to the following in your project.

from django.dispatch.dispatcher import receiver
from allauth.account.signals import user_logged_in

@receiver(user_logged_in, dispatch_uid="unique")
def user_logged_in_(request, user, **kwargs):
    print request.user

This code should be in a place that's likely to be read when django starts up. models.py and views.py are good candidates.

e4c5
  • 52,766
  • 11
  • 101
  • 134
  • Can you update this answer to include just a little more code, so that it's clear where `receiver` and `user_logged_in` get imported from, and how to make sure this function is then called "on startup"? The signals documentation no doubt has that *somewhere*, but having it in this answer will help a lot more people (myself included) – Mike 'Pomax' Kamermans May 05 '17 at 23:10
2

As per the official documentation, there is a signal allauth.account.signals.user_logged_in which gets triggered when a user logs in. This can serve your purpose.

Arun Ghosh
  • 7,634
  • 1
  • 26
  • 38