使用Django 2与Celery 4.1遇ModuleNotFoundError:找不到djcelery模块
Hey there, let's tackle that ModuleNotFoundError you're hitting when your DRF POST endpoint tries to trigger a Celery task. From what you mentioned—version checks coming up clean, but spotting a djcelery reference in Celery's loaders code—this is almost certainly a legacy configuration issue.
Here's how to fix it step by step:
Check your Celery loader configuration
If you've explicitly set a loader in yourcelery.pyfile (likedjcelery.loaders.DjangoLoader), that's the problem. Modern Celery versions (4.x+) have built-in Django integration and don't needdjceleryanymore. Update your Celery app initialization to either:# Option 1: Remove the loader parameter entirely (default uses Django loader) app = Celery('your_project_name') # Option 2: Explicitly use the built-in Django loader app = Celery('your_project_name', loader='django')Uninstall djcelery (if you have it installed)
djceleryis a deprecated package for older Celery versions. If you accidentally installed it, remove it with:pip uninstall djceleryClean up your INSTALLED_APPS
If you addeddjceleryto your Django project'sINSTALLED_APPSsetting, delete that entry. It's not needed for modern Celery-Django setups.Restart services and clear caches
Old configuration data might be stuck in memory. Restart your Celery worker and Django development server, and delete any__pycache__folders in your project to ensure fresh code is loaded.
A quick sanity check: Make sure your celery.py is properly hooked into Django's settings. A standard setup looks like this:
import os from celery import Celery # Set the default Django settings module os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'your_project.settings') app = Celery('your_project') # Load config from Django settings, using CELERY_* prefix app.config_from_object('django.conf:settings', namespace='CELERY') # Auto-discover tasks in all Django apps app.autodiscover_tasks()
The key takeaway here is that djcelery is no longer required for Celery to work with Django—all that functionality is now part of Celery's core. That reference you saw in Celery's loader code is likely leftover legacy code for backward compatibility, but you shouldn't be relying on it.
内容的提问来源于stack exchange,提问作者Alexander

