How can i append two classes in JQuery

2024/10/5 15:00:46

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).

enter image description here

Alert(e.data)

enter image description here

I want something like this:

enter image description here

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>
Answer

This is how i got it working, by getting the value of logged user and other user.

socket.onmessage = function(e) { 
console.log("message", e) 
var chatDataMsg = JSON.parse(e.data) 
//here `me` = $('#myUsername').val() which you alraedy getting in code 
if(chatDataMsg.username == me ){ 
chatHolder.append("<div class='message-list me'>" +  <div class='msg'>" + "<p>" + chatDataMsg.message + "</p>" + "</div>" + "</div>") } else{ 
chatHolder.append("<div class='message-list '>" + "<div class='msg'>" + "<p>" + chatDataMsg.message + "</p>" + "</div>" + "</div>") 
} 
}
https://en.xdnf.cn/q/119066.html

Related Q&A

After installing PyBluez on Windows8.1 I get DLL %1 not valid win32 app

I have installed PyBluez-0.22.win32.exe on a 64bit machine with Python 2.7 (they didnt have a 64bit version). Then I get the following error: ImportError:DLL load failed:%1 is not valid Win32 applicati…

Flask Apache on AWS EC2 - Read/Write Failing

So Ive been stumped by this problem for a day now. Im relatively new to AWS EC2 so have been experimenting with Python Flask apps on it.I have an Ubuntu instance, and can get a flask app to run fine on…

AttributeError: unicode object has no attribute pop

I have this piece of python code in gae.def post(self):cases=self.request.get(cases)while cases:logging.info("cases: %s " % cases)case=cases.pop()Which produces this log.INFO 2012-09-19 2…

How to set platform when using pip download command

I want to download some pacakges(tensorflow, keras, imbalanced, xgboost, lightgbm, catboost) for centos 7.4 and python 3.7 on mac.How should i set platform name and ant other settings?I used below com…

How to split qr codes in separate images?

I have hundreds of pictures with qr codes (sometimes there are 0, 1, 2 or more qr codes on one page...but they are always in one line). I want to decode the qr codes from left to right. My idea is to s…

Python methods from csv

I am working on an assignment where I create "instances" of cities using rows in a .csv, then use these instances in methods to calculate distance and population change. Creating the instance…

Convert string numpy.ndarray to float numpy.ndarray

I have one problem. How can I convert:import numpy as npa = np.array([[0.1 0.2 0.3], [0.3 0.4 0.5], [0.5 0.6 0.7]])To:b = np.array([[0.1,0.2,0.3], [0.3,0.4,0.5], [0.5,0.6,0.7]])

function at the end of code- why do i have to place it?

Im just starting my adventure with Python. Unfortunately, I cant figure out why, at the end of my code, I have to add myfunc(). Without it my code doesnt display. How is it if I use more than one def…

Would like to write code in idle that I have in Jupyter notebook. It is using Timeit

code big_array= np.random.rand(1000000) %timeit sum(big_array) this code above is done in jupyter notebook how do I use this code in idle

How to pass python variable to shell command [duplicate]

This question already has answers here:How to escape os.system() calls?(10 answers)Closed 2 years ago.Is their any way that i can pass variable value of python to my unix command Note : var is a pytho…