如何解决当用户的密码已更改时,在 Django 模型中发送邮件的最佳方式?
我今年刚接触 python 和 django,正在努力弄清楚如何在用户密码更新后通过 send_mail
向用户发送简单的邮件?
我已经通过带有 pre_save
的 Signals 进行了管理,但是我不想让用户等到邮件发送完毕(据我所知,我无法解决这个问题)。使用 post_save
,无法查询之前的状态。
如果我给出以下用户模型,这里最好的方法是什么?
class User(AbstractBaseUser):
id = models.UUIDField(primary_key=True,default=uuid.uuid4,editable=False)
email = models.EmailField(verbose_name="email address",max_length=255,unique=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
USERNAME_FIELD = "email"
REQUIRED_FIELDS = []
# Tells Django that the UserManager class defined above should manage
# objects of this type
objects = UserManager()
def __str__(self):
return self.email
class Meta:
db_table = "login"
我已经使用 pre_save 信号进行了设置,但由于延迟,这对我来说不是解决方案:
@receiver(pre_save,sender=User)
def on_change(sender,instance: User,**kwargs):
if instance.id is None:
pass
else:
previous = User.objects.get(id=instance.id)
if previous.password != instance.password:
send_mail(
"Your password has changed","......","info@examplpe.com",[previous.email],fail_silently=False,)
提前致谢
解决方法
如果您使用自定义模型,您可能可以遍历对 set_password()
的调用以在实例上设置标志,然后检测其在信号中的存在。
试试这个例子:
from django.contrib.auth.models import AbstractBaseUser,PermissionsMixin
from django.db.models.signals import post_save
class User(AbstractBaseUser,PermissionsMixin):
...
def set_password(self,password):
super(User,self).set_password(password)
self._set_password = True
@classmethod
def user_changed(cls,sender,instance,**kwargs):
if getattr(instance,'_set_password',False):
# Send your mail
post_save.connect(User.user_changed,sender=User)
,
您可以覆盖用户模型的保存方法。以下是来自 docs 的示例以及检查 SO 中更改的值:
class User(AbstractBaseUser):
...
__original_password = None
def __init__(self,*args,**kwargs):
super(User,self).__init__(*args,**kwargs)
self.__password = self.password
def save(self,**kwargs):
if self.password != self.__original_password:
notify_user_of_password_change()
super().save(*args,**kwargs) # Call the "real" save() method.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。