python - 电子邮件地址更改时发送电子邮件

标签 python django

在我的 DJango 应用程序中,我想实现一个系统,以便当我的 jmodel MyModel 中的 email 字段发生更改时,会向该电子邮件发送一封电子邮件地址。我的这个模型上有一个 ModelForm。我应该如何以及如何实现这个?

  1. 我应该重写 ModelForm 的 save() 方法并在那里发送电子邮件吗?
  2. 我是否应该 try catch 某种模型更新信号并在那里发送电子邮件 - 如果可以,如何发送?我应该捕获什么信号?

检查电子邮件是否已更改的好方法是什么?这本身是一件微不足道的事情,但我希望代码能够驻留在正确的位置。

谢谢

检查字段是否已更改:Django: When saving, how can you check if a field has changed?

最佳答案

您可以使用django-model-changes无需额外的数据库查找即可执行此操作:

from django.db import models
from django.dispatch import receiver
from django_model_changes import ChangesMixin

class MyModel(ChangesMixin, models.Model):
   # your model

@receiver(pre_save, sender=MyModel)
def send_email_if_changed(sender, instance, **kwargs):
    if 'email' in instance.changes():
        # send email

关于python - 电子邮件地址更改时发送电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7931401/

相关文章:

python - curl 形式的 http post 方法的默认 header 内容类型是什么?

python - flask:记录不会立即更新

django - 在 Django 中添加新的自定义权限

python - 向复杂的 Django View 添加值

django - Dockerfile 运行 python 命令不起作用

python - “标签”对象没有属性 'count'

python - 如何连接多个 pandas.DataFrames 而不会遇到 MemoryError

python - CSV 读取特定行

python - 伯克利咖啡命令行界面

python - Django 休息 : Auth user is not passed to the serialiser error - Field is required