I am attempting to implement sending and receiving messages in a Django template using a for loop. Here is my views function:
@login_required
def message_form(request, id, slug, user_id):
user2 = request.user
user_id = user_id
user = get_object_or_404(User, id=user_id)
msg = Message.objects.filter(sender=user)
post = get_object_or_404(Post, id=id, slug=slug)
post2 = Post.objects.filter(user=post.user)
inbox = Message.objects.filter(reciever=request.user)
sentbox = Message.objects.filter(sender=request.user)
message1 = Message.objects.filter(post=post, sender=user, reciever=post.user).order_by('date')
message2 = Message.objects.filter(post=post, sender=post.user, reciever=user).order_by('date')
reverse=True))
form = MessageForm(request.POST or None)
if request.method == 'POST':
if form.is_valid():
message = form.save(commit=False)
if post.user == request.user:
message.sender = post.user
message.reciever = user
else:
message.sender = request.user
message.reciever = post.user
message.post = post
message.post_user = post.user
message.post_image = post.image1
message.save()
form = MessageForm()
return HttpResponseRedirect('')
context = {
'post': post,
'post2': post2,
'inbox': inbox,
'sentbox': sentbox,
'form': form,
'message1': message1,
'user_id': user_id,
'msg': msg,
'message2': message2,
}
return render(request,'chat.html',context)
And this is the relevant part of the chat.html template:
<div class="border px-2 chat-box">
{% for box in message1 %}
<div class="my-4 border bg-light">
<span class="p-2 my-5">{{ box.msg_content }}</span><br>
<span class="date text-muted">{{ box.whenpublished }}</span>
</div>
{% endfor %}
{% for box2 in message2 %}
<div class="border bg-danger" style="">
<span class="p-2 my-5">{{ box2.msg_content }}</span><br>
<span class="date text-muted">{{ box2.whenpublished }}</span>
</div>
{% endfor %}
</div>
Currently, each sent and received message displays separately. However, I would like the sent message to appear after the received message like this:
hello(user1)
hello(user2)
how are you(user1)
im fine thanks(user2)