2017-09-29 23 views
1

我已閱讀了一些關於該問題的問題,但沒有一個適用於我的案例。 我想在保存新條目時向用戶發送郵件。Django:創建條目時發送郵件給用戶

後/ models.py

from django.db import models 
from django.utils import timezone 
from django.contrib.auth.models import User 
from django.db.models.signals import post_save 
from django.core.mail import EmailMultiAlternatives 
from django.template.loader import render_to_string 
from django.dispatch import receiver 

class Post(models.Model): 
    client = models.ForeignKey(User) 
    date = models.DateTimeField(blank=True, editable=False) 


@receiver(post_save, sender=User) 
def first_mail(sender, instance, **kwargs): 
    if kwargs['created']: 
     user_email = instance.User.email 
     subject, from_email, to = 'New Post', '[email protected]', user_email 

     text_content = render_to_string('post/mail_post.txt') 
     html_content = render_to_string('post/mail_post.html') 

     # create the email, and attach the HTML version as well. 
     msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) 
     msg.attach_alternative(html_content, "text/html") 
     msg.send() 

該信號不發送任何電子郵件。我正在使用mail_panel來跟蹤電子郵件。

+0

'instance.User.email'是否正確? – andi

+1

btw信號發送者應該不在用戶上,但是發佈...已更改,已保存的對象屬於類Post,sot保存後會發出信號 – andi

+0

讓我們知道它是否適合您並接受答案如果是的話) – andi

回答

1

指的Django文檔:

發件人 - 模型類。

https://docs.djangoproject.com/en/1.11/ref/signals/#post-save

因此,如果您節省類崗位的對象,然後將信號發送者後,而不是用戶。

然後在信號您參考instance(這是Post類的對象),並訪問其領域client(FK鏈接,User類的實例),並得到了現場email

適當的形式:

user_email = instance.client.email 

類用戶假定有一個與電子郵件存在字段。

相關問題