Django - 发送有关模型更改的电子邮件

时间:2009-07-21 15:40:41

标签: django email model

我想在模型中更改特定字段时发送电子邮件。可能吗?这是我正在寻找的。我有一个包含BooleanField的配置文件模型,当管理员选择为true时,我想向用户发送电子邮件。我知道我可以把它放在“def save(self):”中,但是,只要模型被更改并且字段为真,它就会触发电子邮件。如果字段从False更改为True,有没有办法让它只有电子邮件?

4 个答案:

答案 0 :(得分:11)

保存方法非常适合您想要做的事情:

def save(self):
    if self.id:
        old_foo = Foo.objects.get(pk=self.id)
        if old_foo.YourBooleanField == False and self.YourBooleanField == True:
            send_email()
    super(Foo, self).save()

答案 1 :(得分:2)

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

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

class MyModel(ChangesMixin, models.Model):
   flag = models.BooleanField()

@receiver(pre_save, sender=MyModel)
def send_email_if_flag_enabled(sender, instance, **kwargs):
    if instance.previous_instance().flag == False and instance.flag == True:
        # send email

答案 2 :(得分:-1)

使用django信号(http://docs.djangoproject.com/en/dev/ref/signals/#django.db.models.signals.post_save)与模型post_save使用钩子函数

在该功能中使用标准的django邮件:http://docs.djangoproject.com/en/dev/topics/email/

答案 3 :(得分:-1)

这样的事情可能有所帮助,只有在从false变为true时发送电子邮件

#models.py
from django.contrib.auth.models import User
from django.db.models import signals
from django.db import models
from django.dispatch import receiver
from django.db.models.signals import pre_save
from django.conf import settings
from django.core.mail import send_mail

#signal used for is_active=False to is_active=True
@receiver(pre_save, sender=User, dispatch_uid='active')
def active(sender, instance, **kwargs):
    if instance.is_active and User.objects.filter(pk=instance.pk, is_active=False).exists():
        subject = 'Active account'
        mesagge = '%s your account is now active' %(instance.username)
        from_email = settings.EMAIL_HOST_USER
        send_mail(subject, mesagge, from_email, [instance.email], fail_silently=False)