NotesWhat is notes.io?

Notes brand slogan

Notes - notes.io

from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth import get_user_model
from .models import Conversation, Message

User = get_user_model()

@login_required
def chat_view(request, username):
# Get the recipient user by username
recipient = get_object_or_404(User, username=username)

# Check if a conversation already exists
conversation = Conversation.objects.filter(participants=request.user).filter(participants=recipient).first()

# If no conversation exists, create a new one
if not conversation:
conversation = Conversation.objects.create()
conversation.participants.add(request.user, recipient)
conversation.save()

# Fetch past messages for the conversation
messages = conversation.messages.all().order_by('timestamp')

return render(request, 'chat/chat_page.html', {
'conversation': conversation,
'messages': messages,
'recipient': recipient,
})



{% extends 'base.html' %}
{% block content %}
<h2>Chat with {{ recipient.username }}</h2>

<div id="chat-log" style="border:1px solid #ccc; padding:10px; height:300px; overflow-y:scroll;">
{% for message in messages %}
{% if message.sender == request.user %}
<p style="text-align:right;"><b>You:</b> {{ message.content }} <small>{{ message.timestamp }}</small></p>
{% else %}
<p style="text-align:left;"><b>{{ message.sender.username }}:</b> {{ message.content }} <small>{{ message.timestamp }}</small></p>
{% endif %}
{% endfor %}
</div>

<input id="chat-message-input" type="text" placeholder="Type a message..." style="width:80%;">
<button id="chat-message-submit">Send</button>

<script>
const chatSocket = new WebSocket(
'ws://' + window.location.host + '/ws/chat/{{ conversation.id }}/'
);

chatSocket.onmessage = function(e) {
const data = JSON.parse(e.data);
const chatLog = document.querySelector('#chat-log');
chatLog.innerHTML += `<p><b>${data.sender}:</b> ${data.message}</p>`;
};

document.querySelector('#chat-message-submit').onclick = function(e) {
const messageInput = document.querySelector('#chat-message-input');
const message = messageInput.value;

chatSocket.send(JSON.stringify({'message': message}));
messageInput.value = '';
};
</script>
{% endblock %}


import json
from channels.generic.websocket import AsyncWebsocketConsumer
from django.contrib.auth import get_user_model
from .models import Conversation, Message

User = get_user_model()

class ChatConsumer(AsyncWebsocketConsumer):
async def connect(self):
# Extract conversation ID from URL
self.conversation_id = self.scope['url_route']['kwargs']['conversation_id']
self.room_group_name = f"chat_{self.conversation_id}"

# Add user to the room group
await self.channel_layer.group_add(self.room_group_name, self.channel_name)
await self.accept()

async def disconnect(self, close_code):
# Remove user from the room group
await self.channel_layer.group_discard(self.room_group_name, self.channel_name)

async def receive(self, text_data):
# Handle incoming messages
text_data_json = json.loads(text_data)
message = text_data_json['message']
sender_username = self.scope['user'].username

# Save the message to the database
conversation = await Conversation.objects.aget(id=self.conversation_id)
sender = await User.objects.aget(username=sender_username)
await Message.objects.acreate(conversation=conversation, sender=sender, content=message)

# Send the message to the room group
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'chat_message',
'message': message,
'sender': sender_username
}
)

async def chat_message(self, event):
# Send the message to WebSocket
await self.send(text_data=json.dumps({
'message': event['message'],
'sender': event['sender'],
}))
     
 
what is notes.io
 

Notes is a web-based application for online taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000+ notes created and continuing...

With notes.io;

  • * You can take a note from anywhere and any device with internet connection.
  • * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
  • * You can quickly share your contents without website, blog and e-mail.
  • * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
  • * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.

Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.

Easy: Notes.io doesn’t require installation. Just write and share note!

Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )

Free: Notes.io works for 14 years and has been free since the day it was started.


You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;


Email: [email protected]

Twitter: http://twitter.com/notesio

Instagram: http://instagram.com/notes.io

Facebook: http://facebook.com/notesio



Regards;
Notes.io Team

     
 
Shortened Note Link
 
 
Looding Image
 
     
 
Long File
 
 

For written notes was greater than 18KB Unable to shorten.

To be smaller than 18KB, please organize your notes, or sign in.