我认为应该验证新的电子邮件地址。如果您的应用程序定期发送电子邮件,您不希望将大量电子邮件发送到用户输入的任何电子邮件地址。
我所做的是允许多个电子邮件地址,直到第二个电子邮件得到验证。然后,按照 elssar 的建议收听 django-allauth 的email_confirmed
信号。验证地址后,将新的电子邮件地址设置为主电子邮件,然后删除任何以前EmailAddess
的 . 这是我最终做的一个简化示例:
楷模:
from django.dispatch import receiver
from allauth.account.models import EmailAddress
from allauth.account.signals import email_confirmed
class CustomUser(models.Model):
...
def add_email_address(self, request, new_email):
# Add a new email address for the user, and send email confirmation.
# Old email will remain the primary until the new one is confirmed.
return EmailAddress.objects.add_email(request, self.user, new_email, confirm=True)
@receiver(email_confirmed)
def update_user_email(sender, request, email_address, **kwargs):
# Once the email address is confirmed, make new email_address primary.
# This also sets user.email to the new email address.
# email_address is an instance of allauth.account.models.EmailAddress
email_address.set_as_primary()
# Get rid of old email addresses
stale_addresses = EmailAddress.objects.filter(
user=email_address.user).exclude(primary=True).delete()
意见:
def update_user_details(request):
user = request.user
new_email = request.POST.get('new_email')
user.custom_user.add_email_address(request, new_email)
...