Django celery: object has no attribute 'delay_on_commit'
django 4.2 with celery 5.5.1
launching a celery task from a django view sometimes causes "'generate_report' object has no attribute 'delay_on_commit'"
# tasks.py
from celery import shared_task
@shared_task
def generate_report(data):
# Code to generate report
...
# django view
def testview(request):
from tasks import generate_report
generate_report.delay_on_commit("mytestdata")
return render(request, "simple_page.html")
This happens on some deployments, but not on all. And when it happens, a server (webapp) reboot solves the issue. Moving the "generate_report" import to the top of the file also did not help.
Note: Code is deployed on pythonanywhere.com with several celery workers running in "always on" tasks.
This turned out to be a misconfiguration, not loading .env where it should have been loaded.
.env is loaded in settings.py (django)
But .env was not loaded in celery.py as it was assumed to be loaded already. This seems not always the case. Sometimes celery.py is run from an _init_ script while .env is not loaded.
This causes celery to run without a valid broker URL, which causes network issues. These network issues cause problems for .delay() and .delay_on_commit()
As I can check, this can be an issue of the versions of Celery. You are trying to use an unsupported version of celery 5.5.1, so you need to switch to 5.3. X and try it.
Supported Celery Versions for Django 4.2:
Celery 5.2.x
Celery 5.3.x