我想在数据库中创建条目时发送邮件,为此我使用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)
答案 0 :(得分:2)
您的信号触发了吗?你注册了吗?
在您的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
,此行必须与您的应用名称和信号所在的文件名匹配