28

I have followed the channels tutorial but while running these error throw

Version of the packages is channels==2.1.2 Django==2.0.4

what I missed ? in settings.py

INSTALLED_APPS = [
   "channels"
    ....
]

ROOT_URLCONF = 'myapp.urls'
ASGI_APPLICATION = "myapp.routing.application"

added file mayapp/routing.py

from channels.routing import ProtocolTypeRouter 

application = ProtocolTypeRouter({
    # Empty for now (http->django views is added by default)
})

this is the error log

System check identified no issues (0 silenced).
August 01, 2018 - 13:11:42
Django version 2.0.4, using settings 'myapp.local_settings'
Starting ASGI/Channels version 2.1.2 development server at http://127.0.0.1:8080/
Quit the server with CONTROL-C.
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f71ecfb6400>
Traceback (most recent call last):
  File "/home/vkchlt0192/myapp/lib/python3.5/site-packages/channels/routing.py", line 33, in get_default_application
    module = importlib.import_module(path)
  File "/home/vkchlt0192/myapp/lib/python3.5/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 986, in _gcd_import
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 956, in _find_and_load_unlocked
ImportError: No module named 'myapp.routing'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/vkchlt0192/myapp/lib/python3.5/site-packages/django/utils/autoreload.py", line 225, in wrapper
    fn(*args, **kwargs)
  File "/home/vkchlt0192/myapp/lib/python3.5/site-packages/channels/management/commands/runserver.py", line 80, in inner_run
    application=self.get_application(options),
  File "/home/vkchlt0192/myapp/lib/python3.5/site-packages/channels/management/commands/runserver.py", line 105, in get_application
    return StaticFilesWrapper(get_default_application())
  File "/home/vkchlt0192/myapp/lib/python3.5/site-packages/channels/routing.py", line 35, in get_default_application
    raise ImproperlyConfigured("Cannot import ASGI_APPLICATION module %r" % path)
django.core.exceptions.ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'myapp.routing'
3
  • Did you get solution ?
    – a_k_v
    Commented Oct 23, 2018 at 12:50
  • now it's working for me, I am using channels==2.1.5 Commented Oct 23, 2018 at 17:19
  • 1
    my case was the syntax problem, such as from channels.routine which should be from channels.routing. and got similar error when py manage.py runserver
    – BingLi224
    Commented Apr 25, 2019 at 16:12

20 Answers 20

18

In my case it was wrong import in different file.

What you should do is

python manage.py shell
from mysite.routing import application

Look what exact error it produces and try to fix that

0
5

Just change

ASGI_APPLICATION = mysite.routing.application

to

ASGI_APPLICATION = "routing.application"

2
  • Don't know why but this fixed the issue.
    – cristian
    Commented Jul 17, 2020 at 8:37
  • Figured it out: the problem was because I had the "routing.py" file in the "mysite/" not in the mysite/mysite/. Adding it there now I can use: ASGI_APPLICATION = mysite.routing.application in seetings file.
    – cristian
    Commented Jul 17, 2020 at 9:49
5

Check for any potential errors (maybe import error) in consumers.py. Also, try to put channels as the first item in INSTALLED_APPS in settings.py.

As stated in channels document:

The Channels development server will conflict with any other third-party apps that require an overloaded or replacement runserver command. An example of such a conflict is with whitenoise.runserver_nostatic from whitenoise. In order to solve such issues, try moving channels to the top of your INSTALLED_APPS or remove the offending app altogether.

1
  • this was the solution! The above error message masks any syntax errors that occurr in that file. Very inconvenient Commented Mar 11, 2020 at 13:43
3

This helped me: Everything with ASGI_APPLICATION was fine (thanks to all the previous answers given here). But I read logs a bit further and it appeared, there was an import error somewhere else:

ImportError: cannot import name 'channel_session_user_from_http' from 'channels.auth'

Once I got rid of it, everything came back on track.

1
  • In my case ImportError: cannot import name 'url' from 'django.conf.urls' Commented Apr 20, 2022 at 20:30
2

You need to put your routing.py file inside mayapp/mayapp/routing.py instead of mayapp/routing.py

3
  • Could you be more specific. File is actually inside the project root directory. It seems right file path !
    – a_k_v
    Commented Oct 23, 2018 at 12:56
  • it's on project root path, now it is working for me after update the channel version to channels==2.1.5 Commented Oct 23, 2018 at 17:20
  • @ShihabudheenKM Can you tell your channels, django and asgiref version? Commented Oct 9, 2019 at 22:34
2

In case anybody comes along this. Remember: ASGI_APPLICATION = "myapp.routing.application" should go at the bottom of settings.py to ensure nothing get snagged in production!

mysite/myapp/routing.py

from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
import myapp.routing

application = ProtocolTypeRouter({
    # (http->django views is added by default)
    'websocket': AuthMiddlewareStack(
        URLRouter(
            myapp.routing.websocket_urlpatterns
        )
    ),
})

myapp/routing.py

from django.urls import path
from . import consumers

websocket_urlpatterns = [
    path('chatroompage', consumers.ChatConsumer),
]
2

Django 2.2 doesn’t have inbuilt ASGI support so we need to use Channel’s fallback alternative. Create myproject/asgi.py like this:

import os

import django
from channels.http import AsgiHandler
from channels.routing import ProtocolTypeRouter

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
django.setup()

application = ProtocolTypeRouter({
  "http": AsgiHandler(),
  # Just HTTP for now. (We can add other protocols later.)
})

source: Channels Docs.

1

in my case there were unresolved packages in consumer.py check if you have any unresolved packages in your channels .py files

1
  • i had the same problem, if there is any error down the "asgi" line, it shows this error
    – SeriForte
    Commented Jan 17, 2021 at 13:32
1

I am also facing the same problem.
Make sure:
=> The routing.py file should be inside the project root folder(i.e. django server, one that has settings.py, wsgi.py,..)
=> In settings.py include, ASGI_APPLICATION = "yourprojectrootname.routing.application"

=>Sometimes, the coding inside routing.py file may generate this error, to check if this is the case remove all the coding and enter the general template coding,

from channels.routing import ProtocolTypeRouter

application = ProtocolTypeRouter({
    # Empty for now (http->django views is added by default)
})

then run the 'python manage.py runserver'. This time if you didn't get any error then problem lies in coding inside routing.py. Debug and fix the issue.

=>In other cases this may be of version problem, downgrading to channels==2.1.2 works

1

When importing your app with absolute path in myapp/routing make sure it is imported like:

import myapp.routing

from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
import myapp.routing

application = ProtocolTypeRouter({
    # (http->django views is added by default)
    'websocket': AuthMiddlewareStack(
        URLRouter(
            myapp.routing.websocket_urlpatterns
        )
    ),
})

It may give you warning as error in PyCharm but you will have working Django channels. I reported it as bug to PyCharm. I hope no one else will spend 3-4 hours on it like me)

1

I have written the below code in asgi.py file, websocket_urlpatterns is imported from routing.py file. This is worked for me.

import os

from django.core.asgi import get_asgi_application

from channels.routing import ProtocolTypeRouter,URLRouter
from channels.auth import AuthMiddlewareStack
from .routing import websocket_urlpatterns


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



application = ProtocolTypeRouter({
    'http': get_asgi_application(),
    'websocket': AuthMiddlewareStack(URLRouter(websocket_urlpatterns))
})
1

try

python3 manage.py shell
>>> from your_project import asgi

if you see below

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/your_project/asgi.py", line 14, in <module>
    from django.core.asgi import get_asgi_application
ModuleNotFoundError: No module named 'django.core.asgi'

your django version is lower than 3.x. asgi is supported after 3.x

found it from here

Django application: No module named 'django.core.asgi'

1

Make sure to remove channels and daphne first.

pip uninstall channels

pip uninstall daphne

Now, Install both channels and daphne together with the below command

python -m pip install -U channels["daphne"]
0

I was also having the same issue i did everything to resolve it, creating another virtual environment and installing older version of Django but after 2 days of hardware i came to realize that my consumers.py file was missing with just a 's' in consumer's' and after that i also corrected in my routing.py file. May be this could be your problem also please do check all the file names first.

0

I've recently faced to this problem, and quickly solved it. After checking the configurations in settings.py and routing.py, I found the problem is in this line:

from channels.auth import AuthMiddlewareStack

the problem is the version compatibility. Then, I upgraded the requirements.txt to the below and it works quiet well.

channels==2.4.0
channels-redis==2.4.2
daphne==2.5.0
0

You should put routing.py inside mysite/mysite/ not mysite/ otherwise you won't be able to use ASGI_APPLICATION = mysite.routing.application in the settings file and you get that error.

0

This problem is course by not importing the get_asgi_application in asgi.py file in settings.py actually had the same issue when i was trying to deploy my app but was able to resolve it by importting get_asgi_application and using it as a traditional http request fallback like so in the asgi.py file :

mport os

from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.security.websocket import AllowedHostsOriginValidator
from django.core.asgi import get_asgi_application
from django.urls import path

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
# Initialize Django ASGI application early to ensure the AppRegistry
# is populated before importing code that may import ORM models.
django_asgi_app = get_asgi_application()

from chat.consumers import AdminChatConsumer, PublicChatConsumer

application = ProtocolTypeRouter({
    # Django's ASGI application to handle traditional HTTP requests
    "http": django_asgi_app,

    # WebSocket chat handler
    "websocket": AllowedHostsOriginValidator(
        AuthMiddlewareStack(
            URLRouter([
                path("chat/admin/", AdminChatConsumer.as_asgi()),
                path("chat/", PublicChatConsumer.as_asgi()),
            ])
        )
    ),
})
-1

I solved my problem by:

  • python manage.py migrate
  • python manage.py makemigrations
  • python manage.py migrate

Also check if you have put the routing.py file in the wrong directory. It should be 'myproject/routing.py'

1
  • You should put routing.py inside mysite/mysite/ not mysite/.
    – cristian
    Commented Jul 17, 2020 at 9:58
-2

Changing define ASGI_APPLICATION variable and CHANNEL_LAYERS.default.ROUTING variable from

<project_name>.routing.application

to

routing.application

With this, I can run properly

-3

Django Version problem


None of the above and other stack overflow answers caused a problem to me I tried the full code from documentation using Django version 3 but without no help and the error still appearing every-time

Solving


solved by downgrading Django version from version 3 to 2.2 and followed the instruction of the 2.2 version (notes section) in the documentation


https://channels.readthedocs.io/en/stable/tutorial/part_1.html

Not the answer you're looking for? Browse other questions tagged or ask your own question.