[Django]-Send confirmation email when changing the email in Django

6👍

I’ve faced the same issue recently. And I didn’t like the idea of having another app/plugin for just that.

You can achieve that by, listening to User model’s singles(pre_save, post_save) and using RegistrationProfile:

signals.py:

from django.contrib.sites.models import Site, RequestSite
from django.contrib.auth.models import User
from django.db.models.signals import post_save, pre_save
from django.dispatch import receiver
from registration.models import RegistrationProfile


# Check if email change
@receiver(pre_save,sender=User)
def pre_check_email(sender, instance, **kw):
    if instance.id:
        _old_email = instance._old_email = sender.objects.get(id=instance.id).email
        if _old_email != instance.email:
            instance.is_active = False

@receiver(post_save,sender=User)
def post_check_email(sender, instance, created, **kw):
    if not created:
        _old_email = getattr(instance, '_old_email', None)
        if instance.email != _old_email:
            # remove registration profile
            try:
                old_profile = RegistrationProfile.objects.get(user=instance)
                old_profile.delete()
            except:
                pass

            # create registration profile
            new_profile = RegistrationProfile.objects.create_profile(instance)

            # send activation email
            if Site._meta.installed:
                site = Site.objects.get_current()
            else:
                site = RequestSite(request)
            new_profile.send_activation_email(site) 

So whenever a User‘s email is changed, the user will be deactivated and an activation email will be send to the user.

Leave a comment