如何触发关于字段更改的电子邮件



我有一个用户可以用来发送投诉的联系表单。但是,我希望支持团队能够指出投诉是否已解决,并且当状态更改为"已解决"时,它将触发电子邮件。默认情况下,投诉处于"未决"状态。我正在使用一个信号。

请,有人可以帮助我,因为它不发送电子邮件时,状态更改为'Resolves'。我做错了什么?

我是这样做的:

@receiver(pre_save, sender=Contact)
def send_email_on_status_change(sender, instance, **kwargs):
# Check if the field that you want to watch has changed
if instance.status == 'Resolved':
# Construct and send the email
subject = "Contact status changed"
message = "the status of this complaint has changed to has changed to '{}'".format(instance)
send_mail(
subject,
message,
'sender@example.com',
['recipient@example.com'],
fail_silently=False,
)

@receiver(pre_save, sender=Contact)
def save_status(sender, instance, **kwargs):
instance.status.save()@receiver(pre_save, sender=Contact)
def send_email_on_status_change(sender, instance, **kwargs):
# Check if the field that you want to watch has changed
if instance.status == 'Resolved':
# Construct and send the email
subject = "Contact status changed"
message = "the status of this complaint has changed to has changed to '{}'".format(instance)
send_mail(
subject,
message,
'sender@example.com',
['recipient@example.com'],
fail_silently=False,
)

class Contact(models.Model):
STATUS_CHOICE = (
("1", "Pending"),
("2", "Resolved"),
)
name = models.CharField(max_length=100)
phone = models.CharField(max_length=15)
email = models.EmailField(max_length=254)
subject = models.CharField(max_length=100)
status = models.CharField(choices=STATUS_CHOICE, default="Pending", max_length=50)
created = models.DateTimeField(auto_now_add=True)
body = models.TextField()
class Meta:
ordering = ["-created"]
verbose_name_plural = "Contacts"
def __str__(self):
return f"Message from: {self.name}"

第一个值保存在数据库中,因此您需要检查该值。将'Resolved'替换为'2'

@receiver(post_save, sender=Contact)
def send_email_on_status_change(sender, instance, **kwargs):
# Check if the field that you want to watch has changed
if instance.status == '2':
# Construct and send the email
subject = "Contact status changed"
message = "the status of this complaint has changed to has changed to '{}'".format(instance)
send_mail(
subject,
message,
'sender@example.com',
['recipient@example.com'],
fail_silently=False,
)

尝试使用postrongave代替pre_save。Postrongave将在使用save()提交数据时触发,因此在那个实例中,状态将被设置为resolved。

还检查信号是否已在您的应用程序中注册。

from django.apps import AppConfig
class MyAppConfig(AppConfig):
name = 'my_app'
def ready(self):
import my_app.signals

最新更新