celery / django-celery-results

Celery result back end with django
Other
668 stars 206 forks source link

`post_save` signal of TaskResult doesn't trigger #395

Open Legend94rz opened 1 year ago

Legend94rz commented 1 year ago

I have custom model that contains a TaskResult as OneToOneField:

class MyModel(models.Model):
    task = models.OneToOneField(TaskResult, on_delete=models.SET_NULL, null=True)
    ...

in my view, I do something like:

@receiver(post_save, sender=TaskResult, dispatch_uid='task_update')
def _on_task_save(sender, instance, **kwargs):
    print("POST_SAVE: ", instance.task_id, instance.id)

def view(request):
    form = models.MyModelForm(data=request.POST)
    if form.is_valid():
        obj :models.MyModel = form.instance
        result = my_celery_task.delay(obj.xxx)
        obj.save()
    return render(request, 'app/index.html')

Then I found the _on_task_save is nerver trigger, but the data is written into the db, which could be checked by python manage.py shell and then run TaskResult.objects.all().

I have found a similar issue https://github.com/celery/django-celery-results/issues/41, but it doesn't solve my problem.

Thanks for any help!

hetvi01 commented 6 months ago

I have used this same approach and it's working for me, just cross verify the below things:

  1. Confirm that the data is being correctly stored in your database by checking for the entry in celery task results table.
  2. Ensure that you've connected the signals file to your app.py file and have included it in the ready function to enable the use of signals.

If everything is set up correctly, the print statement should appear in the terminal where your Celery worker is running.

FraCata00 commented 2 months ago

Follow the instructions by @hetvi01

Example:

app_label -> example

your_project.your_application.apps.py

from django.apps import AppConfig

class ExampleConfig(AppConfig):
    default_auto_field = "django.db.models.BigAutoField"
    name = "example"
    verbose_name = "Examples"

    def ready(self) -> None:
        import example.signals  # noqa: F401