在post_save django上发送邮件

问题描述 投票:0回答:1

我想在数据库中创建条目时发送邮件,为此,我使用django post_save信号,但是我做不到,我不确定我在这里缺少什么有人可以帮助我了解正在发生的变化。我正在使用postmarker进行电子邮件配置。

model.py

class Winner(BaseModel):
    name = models.CharField(max_length=225, blank=True, null=True)
    email = models.EmailField(unique=True, db_index=True)
    telephone = models.CharField(max_length=225, blank=True, null=True)
    postal_code = models.CharField(max_length=225, blank=True, null=True)
    reseller_code = models.CharField(max_length=225, blank=True, null=True)
    company_contact = models.CharField(max_length=225, blank=True, null=True)
    company_name = models.CharField(max_length=225, blank=True, null=True)
    company_telephone = models.CharField(max_length=225, blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True, db_index=True)

    EMAIL_FIELD = 'email'

    class Meta:
        verbose_name = 'winner'
        verbose_name_plural = 'winners'

    def get_email(self):
        """
        Return the indentifying email for this Winner
        """
        return getattr(self, self.EMAIL_FIELD)

    def __str__(self):
        return self.get_email()

signal.py

def send_winner_info(sender, instance, created, **kwargs):
    winner = instance
    if created:
        winner_dict = {
            "Name: ", winner.name,
            "Email: ", winner.email,
            "Telephone: ", winner.telephone,
            "Postal Code: ", winner.postal_code,
            "Reseller Contact: ", winner.reseller_contact,
            "Company Name: ", winner.company_name,
            "Company Telephone: ", winner.company_telephone,
        }
        message = render_to_string('mails/winner.html', winner_dict)
        subject = "Giveaway Winner Information"
        from_email = settings.DEFAULT_FROM_EMAIL
        recipients_list = settings.DEFAULT_RECIPIENT_LIST
        send_mail(subject, message, from_email, recipient_list=recipients_list)


post_save.connect(send_winner_info, sender=Winner)
django django-signals
1个回答
0
投票

您的信号触发了吗?您注册过吗?

在您的apps.py中,在您的应用中,添加以下内容:

from django.apps import AppConfig


class YourAppConfig(AppConfig):
    name = 'your_app_name'

    def ready(self):
        import your_app_name.signal  # noqa

[import your_app_name.signal此行必须与您的应用名称和信号所在的文件名相匹配

© www.soinside.com 2019 - 2024. All rights reserved.