channels: Daphne / ASGI won't use the DJANGO_SETTINGS_MODULE I specify

Hello,

I currently have a problem deploying my Django application with django-channels. I’m trying to setup daphne with nginx and for that, I made this ASGI file:

import os
from channels.asgi import get_channel_layer

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings_production")

channel_layer = get_channel_layer()

But somehow, it keeps using myapp.settings (and thus, fails at the database connection)

I use this command to launch daphne: daphne myapp.asgi:channel_layer -v 2

Python version: 2.7.11+ Django version: 1.9.7 django-channels version: 0.15.0

Am I doing something wrong?

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Comments: 33 (14 by maintainers)

Most upvoted comments

so the issue seems to be with import…

when importing like

from channels.asgi import get_channel_layer

variable should be set before the import like

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings_production")
from channels.asgi import get_channel_layer

Reason being get_channel_layer refers django settings, so get_channel_layer is already imported in the py file with a different DJANGO_SETTINGS_MODULE (default django one)

I would say best approach is making asgi file like

import channels 
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings_production")
channel_layer = channels.asgi.get_channel_layer()

1 year later, it seems like os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings_production")

actually does not change the value of DJANGO_SETTINGS_MODULE os.environ['DJANGO_SETTINGS_MODULE'] = "myapp.settings_production" seems to work better

Don’t create a directory called channels inside your project. It messes with the import statement import channels.asgi. It imports your project’s channels directory. Whoops.

That actually fixed the problem! I was just running python manage.py runworker.

Thank you!

@DarthLabonne Ok one more question, You might be running your workers… daphne just provides the interface actual requests are processed by the workers… how are you staring your workers?.. you might have to provide --settings=routeradmin.settings_production while starting the workers… That might be the problem with your case…

python manage.py runworker --settings=routeradmin.settings_production

You can also update the manage.py file and add os.environ.setdefault("DJANGO_SETTINGS_MODULE", "routeradmin.settings_production") to avoid adding --settings args.

Hope this fixes your problem.