Hello guys, im building chat application and i have encountered a problem.
my models.py
from django.db import models
from django.contrib.auth import get_user_model
from django.contrib.auth.models import User
class Chat(models.Model):
class chatTypes(models.TextChoices):
private = 'private', 'private'
group = 'group', 'group'
chat_type = models.TextField(choices=chatTypes.choices)
participants = models.ManyToManyField(User)
last_message = models.DateTimeField(auto_now=True)
timestamp = models.DateTimeField(auto_now_add=True)
class Message(models.Model):
chat_id = models.ForeignKey(Chat, related_name='chat_messages',
on_delete=models.CASCADE)
content = models.TextField(max_length=1000)
sender = models.ForeignKey(User,related_name='user',on_delete=models.CASCADE)
time_stamp = models.DateTimeField(auto_now_add=True)
my views.py
@login_required
def homepage(request):
chats = Chat.objects.filter(participants=user).prefetch_related('chat_messages').order_by('timestamp')
var = {
'chats': chats,
}
return render(request, 'homepage.html',var)
now in my template i present the user all his chats in a list
{% for chat in chats %}
<div class="chat_item d-flex flex-row">
<p class="friendly_pic"> pic </p>
<div class="chat_item_message d-flex flex-column">
{% if chat.participants.first == request.user %}
<h6> {{ chat.participants.last }} </h6>
{% else %}
<h6> {{ chat.participants.first }} </h6>
{% endif %}
<div class="d-flex flex-row justify-content-between text-muted">
<p class="msg"> {{ chat.chat_messages.last.content }} </p>
<p class="timer"> {{ chat.chat_messages.last.time_stamp|date:'h:i:A' }} </p>
</div>
</div>
</div>
<div class="chat_item_separator" style="color:white">
<hr/>
</div>
{% endfor %}
now what i want to do next is to show the chat message next to the chat lists and each time user click on specific chat that website display the chat mark as active but if i want to filter or get the specific chat_messages that related to the active chat i get error
becuase i cant solve it ill give an example:
{% for chat in chats %}
{% if chat.id == ${active_chat} %}
print chat content
{% endif %}
{% endfor %}
becuase i know django cant accept ${active_chat} value from javascript i tried to move my if statment into the javascript but i cant seem to make it.
ive tried few solutions came to my mind and all failed please im open to suggestions
thanks for your help
edit
i have seen someone over the internet who print all chats content in different div cards and each time add .active to the current card but i think over the time (i do it for training but for example if it was aim for production and lets say there is 1000 chats and each chat has 1000 messages it feels like it is idiotic to make the website create all this divs and each time swap between them) but maybe im wrong and it is the correct way