我将代码设置为每当在数据库中创建新的 PurchaseOrder 时向用户发送电子邮件。电子邮件如下所示:
如您所见,产品字段为空白。它是空白的原因是我正在使用 ManyToManyField 并且不确定如何通过电子邮件将其发送给用户。这是我的代码:
class PurchaseOrder(models.Model):
product = models.ManyToManyField('Product')
def send_email_on_new_order(instance, created, raw, **kwargs):
if not created or raw:
return
title_text = 'This is the title'
body_text = 'Purchase Order System Details' + 'Product: ' + 'Vendor: ' + str(instance.vendor) + 'Price: ' + str(instance.price)
email=EmailMessage(title_text, body_text, to=['youremail@gmail.com'])
email.content_subtype = "html"
email.send()
signals.post_save.connect(send_email_on_new_order, sender= PurchaseOrder, dispatch_uid = 'send_email_on_new_order')
class Product(models.Model):
products = models.CharField(max_length=256)
price_for_each_item = models.FloatField()
def __unicode__(self):
return self.products
基本上我想在电子邮件的 body_text 中包含的是:ManyToManyField 所以它会向用户发送一封电子邮件,其中包含“产品”和“价格_for_each_item”