1

I am using Django signals to trigger a task (sending mass emails to subscribers using Django celery package)when an admin post a blogpost is created from Django admin. The signal is triggered but the task function in the task file is not called. It's because I put a print function which is not printing inside the task function.

My signlas.py file:

from apps.blogs.celery_files.tasks import send_mails
from apps.blogs.models import BlogPost,Subscribers
from django.db.models.signals import post_save
from django.dispatch import receiver

def email_task(sender, instance, created, **kwargs):
    if created:
        print("@signals.py")
        send_mails.delay(5)


post_save.connect(email_task, sender=BlogPost,dispatch_uid="email_task")

My task.py file

from __future__ import absolute_import, unicode_literals
from celery import shared_task
# from celery.decorators import task
from apps.blogs.models import BlogPost,Subscribers
from django.core.mail import send_mail
from travel_crm.settings import EMAIL_HOST_USER
from time import sleep

@shared_task
def send_mails(duration,*args, **kwargs):
    print("@send_mails.py")
    subscribers = Subscribers.objects.all()
    blog = BlogPost.objects.latest('date_created')
    for abc in subscribers:
        sleep(duration)
        print("i am inside loop")
        emailad = abc.email
        send_mail('New Blog Post ', f" Checkout our new blog with title {blog.title} ",
                  EMAIL_HOST_USER, [emailad],
                  fail_silently=False)

Here. the print("@send_mails.py") is not executed but print("@signals.py") in signals.py file is executed. Hence, signals is received after the Blogpost model object is created but the function inside task.py which is send_mails is not executed.

I have installed both celery and redis server and both are working fine.

The main thing is if I remove .delay(5) from signal file and instead used just send_mails() inside email_task , it works perfectly and i am getting emails. But as soon as I add delay() function, the fucntion inside task file is not called. What is the issue??

Reactoo
  • 916
  • 2
  • 12
  • 40

0 Answers0