[英]Best way to send a mail in Django Model when a user's password has been changed?
我今年是 python 和 django 的新手,我只是想知道如何在密碼更新后通過send_mail
向用戶發送簡單的郵件? 我已經通過帶有pre_save
的 Signals 進行了管理,但是我不想讓用戶等到郵件發送完畢(據我所知,我無法解決這個問題)。 使用post_save
,無法查詢到之前的 state。
如果我給以下用戶 model,這里最好的方法是什么?
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,
)
提前致謝
如果您使用的是自定義 model,您可能可以通過調用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)
您可以覆蓋用戶 model 的保存方法。 這是文檔中的一個示例,同時檢查了來自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, *args, **kwargs):
if self.password != self.__original_password:
notify_user_of_password_change()
super().save(*args, **kwargs) # Call the "real" save() method.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.