0

I'm using django channels tutorial and I did whatever there was in the tutorial , and I'm getting error from my Terminal while I click the send button of my message which is: "GET /ws/chat/lobby/ HTTP/1.1" 404 2232

my routing.py file :


from django.urls import re_path

from .consumers import ChatConsumer

websocket_urlpatterns = \[
re_path('ws/chat/\<room_name\>', ChatConsumer.as_asgi()),
\]

my consumers.py :


import json
from channels.generic.websocket import WebsocketConsumer


class ChatConsumer(WebsocketConsumer):
    def connect(self):
        self.accept()

    def disconnect(self, close_code):
        pass

    def receive(self, text_data):
        text_data_dict = json.loads(text_data)
        message = text_data_dict['message']

        self.send(text_data=json.dumps({
            'message': message
        }))

views.py :


from django.shortcuts import render


def index(request):
    return render(request, "chat/index.html")


def room(request, room_name):

    context = {

        "room_name": room_name
    }
    return render(request, 'chat/room.html', context)

urls.py :


from django.urls import path
from .views import index, room
urlpatterns = [
    path('', index, name='index'),
    path('<str:room_name>/', room, name='room')

]

asgi.py file :


import os

from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application
import Chat.routing

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")

application = ProtocolTypeRouter({
  "http": get_asgi_application(),
  "websocket": AuthMiddlewareStack(
        URLRouter(
            Chat.routing.websocket_urlpatterns
        )
    ),
})

and my room.html file :


<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>Chat Room</title>
</head>
<body>
    <textarea id="chat-log" cols="100" rows="20"></textarea><br>
    <input id="chat-message-input" type="text" size="100"><br>
    <input id="chat-message-submit" type="button" value="Send">
    {{ room_name|json_script:"room-name" }}
    <script>
        const roomName = JSON.parse(document.getElementById('room-name').textContent);

        const chatSocket = new WebSocket(
            'ws://'
            + window.location.host
            + '/ws/chat/'
            + roomName
            + '/'
        );

        chatSocket.onmessage = function(e) {
            const data = JSON.parse(e.data);
            document.querySelector('#chat-log').value += (data.message + '\n');
        };

        chatSocket.onclose = function(e) {
            console.error('Chat socket closed unexpectedly');
        };

        document.querySelector('#chat-message-input').focus();
        document.querySelector('#chat-message-input').onkeyup = function(e) {
            if (e.keyCode === 13) {  // enter, return
                document.querySelector('#chat-message-submit').click();
            }
        };

        document.querySelector('#chat-message-submit').onclick = function(e) {
            const messageInputDom = document.querySelector('#chat-message-input');
            const message = messageInputDom.value;
            chatSocket.send(JSON.stringify({
                'message': message
            }));
            messageInputDom.value = '';
        };
    </script>
</body>
</html>

How can I solve this problem?

I tried python manage.py runserver and I got:

Not Found: /ws/chat/lobby/ 
[11/Nov/2022 11:15:36] "GET /ws/chat/lobby/ HTTP/1.1" 404 2232
1
  • Hello, Have you found a solution or more info about how to deal with this? Commented Mar 11, 2023 at 6:42

2 Answers 2

1

I had similar issue and in my case it was the fact that the requests were not processed by an async worker. I had it fixed with: pip install channels[daphne]

then add daphne as the first entry in the INSTALLED_APPS. You may remove channels from the end of the list. Mine works now with this configuration:

INSTALLED_APPS = [
    "daphne",
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "chat.apps.ChatConfig",
]

Daphne takes control of the runserver command. You may not use it if you want, if you add channels at the end INSTALLED_APPS and start a worker separately.

For more information follow the channels tutorial here.

Sign up to request clarification or add additional context in comments.

Comments

0

Possible error, that runserver alias runs wsgi, not asgi application. You should find output like this one after run runserver:

System check identified no issues (0 silenced). April 12, 2024 -
09:57:46 Django version 3.2.1, using settings 'mysite.settings'
**Starting ASGI/Daphne version 4.0.0 development server at**
http://0.0.0.0:8000/ Quit the server with CTRL-BREAK.

Solved the issue by adjusting packages versions (downgraded), below works for me (installed by pip install -U channels["daphne"]):

channels==4.1.0
channels-redis==4.2.0
daphne==4.1.2
Django==5.0.4

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.