Zorgan
Zorgan

Reputation: 9143

ERROR: You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure()

I'm running Celery via Supervisor on my remote Ubuntu server. It's giving me the following error in my celery.log:

 (env) zorgan@app:~/app$ tail /var/log/supervisor/celery.log
        password = models.CharField(_('password'), max_length=128)
      File "/home/zorgan/app/env/lib/python3.5/site-packages/django/db/models/fields/__init__.py", line 1061, in __init__
        super(CharField, self).__init__(*args, **kwargs)
      File "/home/zorgan/app/env/lib/python3.5/site-packages/django/db/models/fields/__init__.py", line 172, in __init__
        self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE
      File "/home/zorgan/app/env/lib/python3.5/site-packages/django/conf/__init__.py", line 56, in __getattr__
        self._setup(name)
      File "/home/zorgan/app/env/lib/python3.5/site-packages/django/conf/__init__.py", line 39, in _setup
        % (desc, ENVIRONMENT_VARIABLE))
    django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, 
    but settings are not configured. You must either define the environment variable 
    DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

even though I've added the value to DJANGO_SETTINGS_MODULE in my celery.py:

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'draft1.settings')

app = Celery("draft1", broker=CELERY_BROKER_URL)
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()

Here is my config /etc/supervisor/conf.d/app-celery.conf if you're curious:

[program:app-celery]
command=/home/zorgan/app/env/bin/celery worker -A draft1 --loglevel=INFO
directory=/home/zorgan/app/draft1

numprocs=1
stdout_logfile=/var/log/supervisor/celery.log
stderr_logfile=/var/log/supervisor/celery.log
autostart=true
autorestart=true
startsecs=10

; Need to wait for currently executing tasks to finish at shutdown.
; Increase this if you have very long running tasks.
stopwaitsecs = 600

stopasgroup=true

; Set Celery priority higher than default (999)
; so, if rabbitmq is supervised, it will start first.
priority=1000

any idea what the problem is?

edit:

__init__.py:

from __future__ import absolute_import, unicode_literals

#This will make sure the app is always imported when
#Django starts so that shared_task will use this app.
from .celery import app as celery_app

__all__ = ['celery_app']

Upvotes: 0

Views: 2849

Answers (1)

anjaneyulubatta505
anjaneyulubatta505

Reputation: 11695

We have to follow the below code.

celery.py

import django
import os

from celery import Celery

os.environ['DJANGO_SETTINGS_MODULE'] = 'draft1.settings'
django.setup()

app = Celery('tasks', broker='amqp://guest@localhost//')

@app.task
def add(x, y):
    return x + y

Reference: http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html

Upvotes: 1

Related Questions