I am new to python and django this year and am just struggling to figure out how to send a simple mail via send_mail
to a user after their password has been updated?
I have managed this via Signals with pre_save
, however I don't want to make the user wait until the mail has been sent (which I can't work around as far as I know). With post_save
, the previous state cannot be queried.
What would be the best way here if I gave the following user 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"
I had set this up with a pre_save signal, but this is not a solution for me because of the delay:
@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,
)
Thanks in advance