HTTP GET /messenger_app/chat_direct/general/? 200 [0.01, 127.0.0.1:49240] WebSocket DISCONNECT /ws/chat/general/ [127.0.0.1:57296]

je travaille sur un projet dont l’objectif est de faire un mini messenger avec des discussions de groupesou non en temps reel mais je rencontre un problème avec l’envoi des messages le terminal retourne ce que vous lisez au titre mais l’envoi ne fonctionne pas. j’ai suivi le didacticiel en question concernant django-channels et les websocket mais cela ne fonctionne toujours pas. si vous pouviez m’aider…
mon asgi.py:

import 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

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'messenger.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 messenger_app.routing import websocket_urlpatterns

application = ProtocolTypeRouter({
    "http": django_asgi_app,
    "websocket": AllowedHostsOriginValidator(
            AuthMiddlewareStack(URLRouter(websocket_urlpatterns))
    ),
    # Just HTTP for now. (We can add other protocols later.)
})

mon settings.py:

INSTALLED_APPS = [
    "daphne",
    'allauth_ui',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'messenger_app',

    #django allauth
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.google',  # Par exemple, pour Google OAuth2

    "widget_tweaks",

    #extension
    "channels",
]
# Configuration du backend de Channels
ASGI_APPLICATION = 'messenger.asgi.application'
AUTH_USER_MODEL = 'messenger_app.CustomUser'

mon urls.py:

from django.contrib import admin
from django.urls import path, include

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('messenger_app/', include('messenger_app.urls')),
    
    #commande pour allauth
    path('accounts/', include('allauth.urls')),

]

if settings.DEBUG:
    urlpatterns +=static(settings.MEDIA_URL,
    document_root=settings.MEDIA_ROOT)

consumers.py:

# /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_json = json.loads(text_data)
        message = text_data_json["message"]

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

routing.py:

# /routing.py
from django.urls import re_path

from . import consumers

websocket_urlpatterns = [
    re_path(r"ws/chat/(?P<room_name>\w+)/$", consumers.ChatConsumer.as_asgi()),
]

views.py:

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


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


def chat_direct(request, room_name):
    return render(request, "chat/chat_direct.html", {'room_name':room_name})

urls.py de l’application:

from django.urls import path
from .import views

urlpatterns = [
    path("", views.index, name = "index"),
    path("chat_group", views.chat_group, name="chat_group"),
    path('chat_direct/<str:room_name>/', views.chat_direct, name='chat_direct'),
    path("chat_empty", views.chat_empty, name="chat_empty"), 
    path("lockscreen", views.lockscreen, name="lockscreen"),
    path("password_reset", views.password_reset, name="password_reset"),
    path("signup", views.signup, name="signup"),
    path("signin", views.signin, name="signin"),

    path('conversation/<int:pk>/', views.conversation_detail, name='conversation_detail'),

    #path send_mail
    path("envoyer_email", views.envoyer_email, name="envoyer_email"),
]

mon chat_direct.html:

<!-- Message -->
                                        <div class="message message-out" id="chat-log">
                                            <a href="#" data-bs-toggle="modal" data-bs-target="#modal-profile" class="avatar avatar-responsive">
                                                <img class="avatar-img" src="{% static 'assets/img/avatars/1.jpg' %}" alt="">
                                            </a>

                                            <div class="message-inner">
                                                <div class="message-body">
                                                    <div class="message-content">
                                                        <div class="message-text">
                                                            <p>Hey, Marshall! How are you? Can you please change the color theme of the website to pink and purple? 😂</p>
                                                        </div>

                                                        <!-- Dropdown -->
                                                        <div class="message-action">
                                                            <div class="dropdown">
                                                                <a class="icon text-muted" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                                                                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-more-vertical"><circle cx="12" cy="12" r="1"></circle><circle cx="12" cy="5" r="1"></circle><circle cx="12" cy="19" r="1"></circle></svg>
                                                                </a>

                                                                <ul class="dropdown-menu">
                                                                    <li>
                                                                        <a class="dropdown-item d-flex align-items-center" href="#">
                                                                            <span class="me-auto">Edit</span>
                                                                            <div class="icon">
                                                                                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-edit-3"><path d="M12 20h9"></path><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"></path></svg>
                                                                            </div>
                                                                        </a>
                                                                    </li>
                                                                    <li>
                                                                        <a class="dropdown-item d-flex align-items-center" href="#">
                                                                            <span class="me-auto">Reply</span>
                                                                            <div class="icon">
                                                                                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-corner-up-left"><polyline points="9 14 4 9 9 4"></polyline><path d="M20 20v-7a4 4 0 0 0-4-4H4"></path></svg>
                                                                            </div>
                                                                        </a>
                                                                    </li>
                                                                    <li>
                                                                        <hr class="dropdown-divider">
                                                                    </li>
                                                                    <li>
                                                                        <a class="dropdown-item d-flex align-items-center text-danger" href="#">
                                                                            <span class="me-auto">Delete</span>
                                                                            <div class="icon">
                                                                                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-trash-2"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path><line x1="10" y1="11" x2="10" y2="17"></line><line x1="14" y1="11" x2="14" y2="17"></line></svg>
                                                                            </div>
                                                                        </a>
                                                                    </li>
                                                                </ul>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>

                                                <div class="message-footer">
                                                    <span class="extra-small text-muted">08:45 PM</span>
                                                </div>
                                            </div>
                                        </div>

<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.key === 'Enter') {  // 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>

It would be more helpful if you provided more details about what exactly is not working.

What sort of information are you seeing in your browser’s developer tools network tab for the web socket?

Your JavaScript seems to be working with elements named chat-message-input and chat-message-submit, but I don’t see where they’re defined in your template. Where are those elements defined?

sur mon js j’ai trois éléments : #chat-message-input, #chat-message-submit et #chat-log. #chat-message-input c’est le textarea ou j’ecris mon message, #chat-message-submit c’est pour l’envoi et #chat-log c’est ou je vois les messages envoyés ou reçus. voilà le code :

 <!-- Chat: Form -->
                                <form class="chat-form rounded-pill bg-dark" data-emoji-form="">
                                    <div class="row align-items-center gx-0">
                                        <div class="col-auto">
                                            <a href="#" class="btn btn-icon btn-link text-body rounded-circle" id="dz-btn">
                                                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-paperclip">
                                                    <path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"></path>
                                                </svg>
                                            </a>
                                        </div>
                            
                                        <div class="col">
                                            <div class="input-group">
                                                <textarea id="chat-message-input" class="form-control px-0" placeholder="Type your message..." rows="1" data-emoji-input="" data-autosize="true"></textarea>
                            
                                                <a href="#" class="input-group-text text-body pe-0" data-emoji-btn="">
                                                    <span class="icon icon-lg">
                                                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-smile">
                                                            <circle cx="12" cy="12" r="10"></circle>
                                                            <path d="M8 14s1.5 2 4 2 4-2 4-2"></path>
                                                            <line x1="9" y1="9" x2="9.01" y2="9"></line>
                                                            <line x1="15" y1="9" x2="15.01" y2="9"></line>
                                                        </svg>
                                                    </span>
                                                </a>
                                            </div>
                                        </div>
                            
                                        <div class="col-auto">
                                            <button id="chat-message-submit" class="btn btn-icon btn-primary rounded-circle ms-5">
                                                {{ room_name|json_script:"room-name" }}
                                                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-send">
                                                    <line x1="22" y1="2" x2="11" y2="13"></line>
                                                    <polygon points="22 2 15 22 11 13 2 9 22 2"></polygon>
                                                </svg>
                                            </button>
                                        </div>
                                    </div>
                                </form>

dans le precedant code associé avec le js vous verrez le #chat-log
maintenant ce qui ne fonctionne pas c’est que lorsque j’envoi un message il n’apparait pas dans l’espace #chat-log.
et voila les infos que je vois dans l’onglet reseau sur cette image:

In the “Messages” section of those tools, are you seeing your messages being sent?

If so, then please post the messages you’re seeing submitted.

If not, then you’ve got an error in your JavaScript code.

non justement il n’y a aucun messages ni envoyés ni reçu

quel pourrait donc bien être l’événement js qui bloque l’envoi des messages? puisque c’est le js que j’ai pris sur le didacticiel concernant channels et les websockets. et je je l’ai essayé par à pas sur un projet vide et cela a fonctionné normalement sans problème mais en l’adaptant à mon code que je vous ai fourni il n’y a plus le même résultat

In this case then, I would go back to the simpler version that works, and try to build incrementally from there. Make the smallest changes you can until you identify which change was made that causes it to not work any more.

d’accord merci beaucoup j’vous tiens informé de la suite du fonctionnement