django 如何触发字段变更邮件

5rgfhyps  于 2022-12-20  发布在  Go
关注(0)|答案(2)|浏览(138)

我有一个用户可以用来发送投诉的联系表单。但是,我希望支持团队可以指示投诉是否已解决,并且在状态更改为“已解决”时会触发电子邮件。默认情况下,投诉为“待定”。我目前正在使用信号。
请,有人能帮助我,因为它不发送电子邮件时,状态更改为“解决”。我做错了什么?
我是这么做的:

@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}"
kxxlusnw

kxxlusnw1#

第一个值保存在数据库中,因此您需要检查该值。请将“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,
        )
e0bqpujr

e0bqpujr2#

尝试使用post_保存而不是pre_save。Post_save将在使用save()提交数据时触发,因此在该示例中,状态将设置为已解决。
同时检查信号是否已在您的应用中注册。

from django.apps import AppConfig

class MyAppConfig(AppConfig):
    name = 'my_app'

    def ready(self):
        import my_app.signals

相关问题