在 Django 中更改电子邮件时发送确认电子邮件

Osc*_*ros 3 django registration django-registration

我目前正在使用django-registration,并且运行良好(有一些技巧)。当用户注册时,他必须检查他/她的邮件并点击激活链接。那很好,但是...

如果用户更改电子邮件怎么办?我想给他/她发送一封电子邮件,以确认他是该电子邮件地址的所有者...

是否有应用程序、代码片段或其他东西可以节省我自己编写的时间

小智 5

我最近遇到了同样的问题。我不喜欢为此而拥有另一个应用程序/插件的想法。

您可以通过聆听User模特的单曲(pre_savepost_save)并使用RegistrationProfile

信号.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) 
Run Code Online (Sandbox Code Playgroud)

因此,每当 aUser的电子邮件发生更改时,用户将被停用,并且将向用户发送一封激活电子邮件。