首先创建一个signals.py文件
# 假设有一个博客应用程序,每当有新文章发表时,给订阅用户发送一封邮件通知
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.core.mail import send_mail
from django.conf import settings
from .models import BlogPost
@receiver(post_save, sender=BlogPost)
def notify_subscribers(sender, instance, created, **kwargs):
if created:
subject = f"New blog post: {instance.title}"
message = f"A new blog post has been published: {instance.title}. Visit {settings.SITE_URL} to read it."
from_email = settings.DEFAULT_FROM_EMAIL
recipient_list = [subscriber.email for subscriber in Subscriber.objects.all()]
send_mail(subject, message, from_email, recipient_list, fail_silently=False)
# 在这个例子中,我们定义了一个接收器notify_subscribers,监听BlogPost模型的post_save信号。如果一个新文章被创建(created=True),则发送一封邮件给所有订阅者。
在apps.py中导入创建的信号
# myapp/apps.py
from django.apps import AppConfig
class MyAppConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'myapp'
# 在这里导入创建的信号,在应用的所有组件都被Django加载之后,信号处理器才会被连接
def ready(self):
import myapp.signals
注意事项
# 当保存或删除模型实例时,post_save和post_delete信号会被自动触发
# pre_save、pre_delete与post_save、post_delete的区别:
"""
pre_save:
在模型实例被保存到数据库之前触发
pre_delete:
在模型实例被删除前触发
post_save:
在模型实例被成功保存到数据库后触发
post_delete:
在模型实例被成功从数据库中删除后触发
"""