Django使用自定义信号发送邮件

时间:2013-03-22 05:35:36

标签: django django-views django-signals

在我的示例中,信号函数是在models.py中创建的。相反,我认为可以使用自定义信号概念。

我的models.py for signals功能是

class Book(models.Model):
    [..........]

def send_update(sender, instance, created, **kwargs):
    if instance.author_name:
        message = "Book is updated"
        subject = "Updates"
        send_mail(subject, message, your_email,
            [instance.email,])

post_save.connect(send_update, sender=Book)

views.py是

if request.POST:
        form = BookForm(request.POST)

        if form.is_valid():
            cd = form.cleaned_data
            form.save()
            return redirect('/index/')
    return render_to_response('addbook.html',{ 'form':form },context_instance=RequestContext(request))

除了这个,我们如何使用signals.py文件创建自定义信号来发送邮件。

我试图在实践中学习这一点,一个例子将帮助我做到这一点。

谢谢

2 个答案:

答案 0 :(得分:10)

<强> signals.py

from django.db.models.signals import post_save
from app.models import Book

def send_update(sender, instance, created, **kwargs):
    if instance.author_name:
        message = "Book is updated"
        subject = "Updates"
        send_mail(subject, message, your_email,
            [instance.email,])

post_save.connect(send_update, sender=Book)

通过在应用程序的__init__.py文件中导入信号来注册信号。这将允许来自import models的{​​{1}}。

signals.py

__init__.py

答案 1 :(得分:1)

signals.py中定义您的信号和接收器:

from django.dispatch import Signal

post_update = Signal(providing_args = ['instance'])

def send_update(...):
    ....

post_update.connect(send_update, sender = Book)

views.py中,在保存表单后立即发送信号:

instance = form.save()
post_update.send(sender = Book, instance = instance)