当管理员发布从 Django 管理员创建的博客文章时,我使用 Django 信号触发任务(使用 django celery 包向订阅者发送大量电子邮件)。但信号没有被触发。我在信号内有一个未打印的打印语句,即创建新博客后未收到信号。
我的应用程序是这样设置的。
我的博客模型:
class BlogPost(models.Model):
author = models.CharField(max_length=64, default='Admin')
image = models.ImageField(blank=True, null=True)
title = models.CharField(max_length=255)
.................../
我的任务文件
from django.core.mail import send_mail
from travel_crm.settings import EMAIL_HOST_USER
@shared_task
def send_mails(self,*args, **kwargs):
subscribers = self.kwargs['subscribers']
blog = self.kwargs['blog']
for abc in subscribers:
emailad = abc.email
send_mail('New Blog Post ', f" Checkout our new blog with title {blog.title} ",
EMAIL_HOST_USER, [emailad],
fail_silently=False)
我的signals.py文件
from .tasks import send_mails
from apps.blogs.models import BlogPost,Subscribers
from django.db.models.signals import post_save
from django.dispatch import receiver
@receiver(post_save, sender=BlogPost)
def email_task(sender, instance, created, **kwargs):
print(123456789)
if created:
print(123456789)
subscribers = Subscribers.objects.all()
blog = BlogPost.objects.latest('date_created')
print(blog)
# task = send_mails(subscribers, blog)
# task.delay()
send_mails.delay(subscribers,blog)
我的初始化文件
from __future__ import absolute_import, unicode_literals
from apps.blogs.celery_files.celery import app as celery_app
__all__ = ('celery_app',)
您必须将您的
signals.py
导入到某个地方才能注册,django文档建议将其导入到应用程序的ready()
文件中的apps.py
方法中,如下所示:
from django.apps import AppConfig
class BlogsConfig(AppConfig):
name = 'blogs'
def ready(self):
import blogs.celery_files.signals
https://docs.djangoproject.com/en/3.2/topics/signals/#connecting-receiver-functions
检查您的我的任务文件文件。您分享了整个文件吗?
你写道:
from django.core.mail import send_mail
from travel_crm.settings import EMAIL_HOST_USER
@shared_task
def send_mails(self,*args, **kwargs):
subscribers = self.kwargs['subscribers']
blog = self.kwargs['blog']
for abc in subscribers:
emailad = abc.email
send_mail('New Blog Post ', f" Checkout our new blog with title {blog.title} ",
EMAIL_HOST_USER, [emailad],
fail_silently=False)
如果这是整个文件,则您有多个问题需要修复:
@shared_task
装饰器而没有相应的导入
from celery import shared_task
self
参数您在 Signals.py 中也有同样的意图问题。
在您的情况(任务)中,保存方法不会触发信号。因为它正在 Django 进程之外运行。 Django 信号有点令人困惑。如果您熟悉文档,您会期望它能够工作。但实际上信号仅从 Django 上下文发送(视图、管理、表单……)