I have implemented a chat box message (live chat) using django and now i want to add css, but i have problem on how to append multiple classes on messege sent. For example, i want to show other user messages float left and current user messages float right. But when i submit messages is displays only on float right, because i am only appending one class to messege sent. I think this is because i am only appending class="message-list me", when i change class="message-list" this display all message to the left. How do i float each message to left and right?
This is what i got: haha should float to right (flex-start), while pepe should float to left (flex-end).
Alert(e.data)
I want something like this:
consumers.py
class ChatConsumer(AsyncConsumer):async def websocket_connect(self, event):print('connected', event)other_user = self.scope['url_route']['kwargs']['username']me = self.scope['user']thread_obj = await self.get_thread(me, other_user)self.thread_obj = thread_objchat_room = f"thread_{thread_obj.id}"self.chat_room = chat_roomawait self.channel_layer.group_add(chat_room,self.channel_name)await self.send({"type": "websocket.accept"})async def websocket_receive(self, event):# when a message is recieved from the websocketprint("receive", event)front_text = event.get('text', None)if front_text is not None:loaded_dict_data = json.loads(front_text)msg = loaded_dict_data.get('message')user = self.scope['user']username = 'default'if user.is_authenticated:username = user.usernamemyResponse = {'message': msg,'username': username}await self.create_chat_message(user, msg)# broadcasts the message event to be sent, the group send layer# triggers the chat_message function for all of the group (chat_room)await self.channel_layer.group_send(self.chat_room,{"type": "chat_message","text": json.dumps(myResponse)})# chat_method is a custom method name that we made
async def chat_message(self, event):#sends the actual messageawait self.send({"type": "websocket.send","text": event['text']})async def websocket_disconnect(self, event):# when the socket disconnectsprint('disconnected', event)@database_sync_to_async
def get_thread(self, user, other_username):return Thread.objects.get_or_new(user, other_username)[0]@database_sync_to_async
def create_chat_message(self, me, msg):thread_obj = self.thread_objreturn ChatMessage.objects.create(thread=thread_obj, user=me, message=msg)
Template:
<div class="message-wrap" id='chat-items'>{% for chat in object.chatmessage_set.all %}<div class="message-list">{% if request.user != chat.user %}<div class="msg"><p>{{ chat.message }}</p></div><div class="time">{{ chat.timestamp }}</div>{% endif %}</div><div class="message-list me">{% if request.user == chat.user %}<div class="msg"><p>{{ chat.message }}</p></div><div class="time">{{ chat.timestamp }}</div>{% endif %}</div>{% endfor %}</div><h3>Thread for {% if user != object.first %}{{ object.first }}{% else %}{{ object.second }}{% endif %}</h3>
<ul id='chat-items'>
{% for chat in object.chatmessage_set.all %}<li>{{ chat.message }} via {{ chat.user }}</li>{% endfor %}
</ul><form id='form' method='POST'> {% csrf_token %}
<input type="hidden" id="myUsername" value="{{ user.username }}" />
{{form.as_p }}
<input type='submit' class='btn btn-primary'/>
</form>
CSS:
.message-wrap .message-list {
align-self: flex-start; #float start
max-width: 70%;
}
.message-wrap .message-list.me {
align-self: flex-end; #float at the end
}
.message-wrap .message-list.me .msg {
background: #bde2f7;
color: #111;
}
.message-wrap .message-list .msg {
background: #fff;
box-shadow: 0 5px 15px -5px rgba(0, 0, 0, 0.1);
padding: 10px 5px;
margin-bottom: 10px;
border-radius: 5px;
}
JQuery:
<!-- Channels Reconnecting Websocket -->
<script src='https://cdnjs.cloudflare.com/ajax/libs/reconnecting-websocket/1.0.0/reconnecting-websocket.js'></script> <script>
// websocket scripts - client side*
var loc = window.location
var formData = $("#form")
var msgInput = $("#id_message")
var chatHolder = $('#chat-items')
var me = $('#myUsername').val()var wsStart = 'ws://'
if (loc.protocol == 'https:') {wsStart = 'wss://'
}
var endpoint = wsStart + loc.host + loc.pathname
var socket = new ReconnectingWebSocket(endpoint)// below is the message I am receiving
socket.onmessage = function(e) {console.log("message", e)var chatDataMsg = JSON.parse(e.data)chatHolder.append("<div class='message-list me'>" + "<div class='msg'>" + "<p>" + chatDataMsg.message + "</p>" + "</div>" + "</div>")
}
// below is the message I am sending
socket.onopen = function(e) {console.log("open", e)formData.submit(function(event){event.preventDefault()var msgText = msgInput.val()//chatHolder.append("<li>" + msgText + " via " + me + "</li>")var finalData = {'message': msgText}socket.send(JSON.stringify(finalData))formData[0].reset()})
}
socket.onerror = function(e) {console.log("error", e)
}
socket.onclose = function(e) {console.log("close", e)
}
</script>