#1 Le 02/06/2024, à 20:27
- brice_dev
[Résolu] TypeError: index() missing 1 required positional argument
j'ai ajouté l'extension channels de python django mais je rencontre des buggs d'arguments sur une de mes vues django pourtant elle existe. j'ai deja checker les discussions et je n'ai pas vu de problème semblables pour pouvoir corriger de moi même. je suis ouvert à toute eventuelle aide merci. @all_menbers
ma views.py:
from django.shortcuts import render, get_object_or_404
from .models import Conversation, Message
from .forms import MessageForm
#pour l'envoi des mails
from django.core.mail import send_mail
from django.http import HttpResponse
from django.conf import settings
# Create your views here.
# methode d'envoi d'un email en django
def envoyer_email(request):
sujet = 'vous avez recu un mail d\'un developpeur pro'
message = 'Bonjour ici Brice_Dev, developpeur BackEnd professionnel'
adresse_email = 'bnkega@gmail.com'
envoyeur = settings.EMAIL_HOST_USER
try:
send_mail(sujet, message, envoyeur, [adresse_email])
return HttpResponse('Email envoyé avec succès')
except:
return HttpResponse('Erreur lors de l\'envoi de l\'email')
def conversation_detail(request, pk):
conversation = get_object_or_404(Conversation, pk=pk)
messages = Message.objects.filter(conversation=conversation).order_by('timestamp')
if request.method == 'POST':
form = MessageForm(request.POST, request.FILES)
if form.is_valid():
message = form.save(commit=False)
message.sender = request.user
message.conversation = conversation
message.save()
else:
form = MessageForm()
return render(request, 'your_app/conversation_detail.html', {'conversation': conversation, 'messages': messages, 'form': form})
def index(request, room_name):
return render(request, "index.html", {'room_name':room_name})
mon urls.py:
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", 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"),
]
le formulaire pour l'envoi du message:
<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 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 class="btn btn-icon btn-primary rounded-circle ms-5">
<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>
le script qui gere l'envoi du message et la connexion au socket:
<script>
const roomName = "{{ room_name }}";
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 key
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>
mon settings.py:
INSTALLED_APPS = [
'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'
#omposant pour la communication entre différentes parties de l'application via des canaux (channels)
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
"hosts": [('127.0.0.1', 6379)],
},
},
}
mon asgi.py:
import os
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from messenger_app.routing import websocket_urlpatterns
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'messenger.settings')
application = ProtocolTypeRouter({
"http": get_asgi_application(),
"websocket": AuthMiddlewareStack(
URLRouter(
websocket_urlpatterns
)
),
})
mon consumers.py:
import json
from channels.generic.websocket import AsyncWebsocketConsumer
class ChatConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.room_name = self.scope['url_route']['kwargs']['room_name']
self.room_group_name = f'chat_{self.room_name}'
# Rejoindre la salle
await self.channel_layer.group_add(
self.room_group_name,
self.channel_name
)
await self.accept()
async def disconnect(self, close_code):
# Quitter la salle
await self.channel_layer.group_discard(
self.room_group_name,
self.channel_name
)
# Recevoir un message du WebSocket
async def receive(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json['message']
# Envoyer le message à la salle
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'chat_message',
'message': message
}
)
# Recevoir un message de la salle
async def chat_message(self, event):
message = event['message']
# Envoyer le message au WebSocket
await self.send(text_data=json.dumps({
'message': message
}))
mon routing.py:
from django.urls import path
from . import consumers
websocket_urlpatterns = [
path('ws/chat/<str:room_name>/', consumers.ChatConsumer.as_asgi()),
]
Dernière modification par Ayral (Le 07/06/2024, à 22:47)
Hors ligne