pythondjangodjango-authenticationdjango-signals

Detect a changed password in Django


When a user changes their password, I want to send a signal so that I can do some stuff on some models.

How can I create this signal?

I've looked at the post_save signal for User:

post_save.connect(user_updated, sender=User)

However, there doesn't seem to be anything in there for me to check if the password was changed:

def user_updated(sender, **kwargs):
    print(kwargs) # {'created': False, 'raw': False, 'instance': <User: 100002>, 'update_fields': None, 'signal': <django.db.models.signals.ModelSignal object at 0x7ff8862f03c8>, 'using': 'default'}

I also see that there is a password_change_done auth view, but I'm not sure how I'd use it. https://docs.djangoproject.com/en/1.10/topics/auth/default/#built-in-auth-views

Any ideas?


Solution

  • You could use a pre_save signal. kwargs['instance'] will contain the updated password and you can get the old password with User.objects.get(id= user.id).password

    @receiver(pre_save, sender=User)
    def user_updated(sender, **kwargs):
        user = kwargs.get('instance', None)
        if user:
            new_password = user.password
            try:
                old_password = User.objects.get(id=user.id).password
            except User.DoesNotExist:
                old_password = None
            if new_password != old_password:
            # do what you need here