'Display value from specific model/queryset once POSTED to template Django
This is my code for the view
def return_chat(request):
context = {'client_name': request.POST['client_name'], 'messages': [], 'datetime': []}
def order_messages():
replies = Replies.objects.all().filter(unique_num=request.POST['unique_num'])
sent_messages = InstantMessages.objects.all().filter(unique_num=request.POST['unique_num']) + 'S'
from itertools import chain
all_messages = list(chain(replies, sent_messages))
all_messages.sort(key=lambda x: x.datetime)
return all_messages
for item in order_messages():
context['messages'].append(item.message)
context['datetime'].append(item.datetime)
return render(request, 'chat.html', context)
My HTML code:
<html>
<body>
<div style="position:relative;background-color:#f5f5f5;width:900px;height:500px;border-radius:15px;border:2px solid black;margin:auto;margin-top:10%;">
<div style="position:absolute;left:20px;padding:10px;top:15px;border-left-style:solid;border-left-color:#48b8fa;margin:auto;width:870px;max-height:350px;overflow-y:scroll;">
{% for all_messages in messages %}
<br>
{{ all_messages }}
<br>
{% endfor %}
</div>
<textarea placeholder="Type your message to {{ client_name }} here.." style="background-color:#f5f5f5;position:absolute;width:900px;height:90px;border-bottom-left-radius:15px;border-bottom-right-radius:15px;bottom:0;border:2px solid black;right:-2px;bottom:-2px;padding:20px;margin:auto;padding-right:80px"></textarea>
<button style="position:absolute;width:80px;height:90px;border-bottom-right-radius:15px;bottom:0;border:2px solid black;right:-2px;bottom:-2px;"><b>Send</b></button>
</div>
</body>
</html>
Essentially. I want the replies on the left and the InstantMessages to appear on the right side in the Django template. Currently, they are both displayed with no difference. I want to know how to reference them independently.
Solution 1:[1]
You can have an identifier that distinguish message between "replies" and "instant messages". Consider you have a field called "message_type" in both models "InstantMessages" and "Replies". In both models, "message_type" definition is same and it accepts any one value from ['recieved' , 'sent'].
Now every object of "Replies" and "InstantMessages" models have this field "message_type". In template, depending on this field value, you can set the style so that text appears left or right.
<div style="......."> {% for all_messages in messages %} {% if message.message_type="sent"%} <div style="text-align:right">{{message}}</div> {% else %} <div style="text-align:left">{message}</div> {% endif %} {% endfor %} </div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | B.Anup |

