Search code examples
djangocelerydjango-celery

Django and celery: What is the need for setting DJANGO_SETTINGS_MODULE for the 'celery' program since its already set in manage.py


While i was understanding how to use celery i found the following

import os
from celery import Celery

# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'projectname.settings')
app = Celery('projectname')

In the above code we are setting the env variable DJANGO_SETTINGS_MODULE

It's the same thing we do in the manage.py

def main():
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'projectname.settings')

Since DJANGO_SETTINGS_MODULE its being set in the manage.py why to set it again in celery

I checked the DJANGO_SETTINGS_MODULE is already set. I commented out and printed the env variable:

import os
from celery import Celery

# set the default Django settings module for the 'celery' program.
#os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'projectname.settings')

print("DJANGO_SETTINGS_MODULE [celery.py] : ",os.environ.get("DJANGO_SETTINGS_MODULE"))

app = Celery('projectname')

then

$ python manage.py runserver

output:

DJANGO_SETTINGS_MODULE [celery.py] :  projectname.settings

So i feel its not needed.


Solution

  • It's so that celery can auto discover tasks in your app modules. Celery isn't started with manage.py it's started similar to below

    $ celery -A proj worker -l info
    

    When this command is run in the shell Celery executes the code in proj/celery.py which exports Django settings and looks for tasks.py in your project apps.