1👍
✅
Holy crap.. Figured it out. Hope this helps somebody else when using django templates and channels websockets (check all template variables carefully…)
- There were no
console.log
messages because I was missing{% block scripts %}
and{% endblock %}
at the bottom of my base.html file. - Once fixing this the websockets connected.
- After fixing those things then the
Request aborted Forbidden (CSRF token missing.)
message disappeared.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{% block title %}{% endblock %}DjangoChat</title>
<script src="https://cdn.tailwindcss.com"></script>
<link rel="stylesheet" href="">
</head>
<body class="bg-teal-600">
<nav class="flex items-center justify-between px-4 py-6 bg-teal-800">
<div>
<a href="/" class="text-xl text-white">Django Chat</a>
</div>
<div class="flex items-center space-x-4">
{% if request.user.is_authenticated %}
<a href="/chats/" class="text-white hover:text-grey-200">Chats</a>
<a href="/logout/" class="px-5 py-3 rounded-xl text-white bg-teal-600 hover:bg-teal-700">Log out</a>
{% else %}
<a href="/login/" class="text-white hover:text-grey-200">Login</a>
<a href="/signup/" class="px-5 py-3 rounded-xl text-white bg-teal-600 hover:bg-teal-700">Sign Up</a>
{% endif %}
</div>
</nav>
{% block content %}
{% endblock %}
{% block scripts %}
{% endblock %}
</body>
</html>
Also there’s a typo in the chat.html, #chat-message-input
not #chat-massage-input
and chat.html form needs to be updated with csrf_token:
<div class="lg:w-2/4 mt-6 mx-4 lg:mx-auto p-4 bg-white rounded-xl">
<form method="post" action="." class="flex">
{% csrf_token %}
<input type="text" name="content" class="flex-1 mr-3" placeholder="Your message..." id="chat-message-input">
<button class="px-5 py-3 rounded-xl text-white bg-teal-600 hover:bg-teal-700" id="chat-message-submit">Submit</button>
</form>
</div>
lastly consumers.py disconnect needs to be changed:
async def disconnect(self, code):
await self.channel_layer.group_discard(
self.chat_group_name,
self.channel_name
)
now I can send messages successfully.
Source:stackexchange.com