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>