I am building a chat application in Django. But I have a problem with displaying the last 25 messages of my chat. Here is my code.... This is my model for saving the messages:
from django.contrib.auth import get_user_model
from django.db import models
class Message(models.Model):
username = models.CharField(max_length = 255)
room = models.CharField(max_length = 255)
content = models.TextField()
date_added = models.DateTimeField(auto_now_add = True)
class Meta:
ordering = ('date_added', )
Here is the function that should filter the messages and render the template in views :
@login_required(login_url = 'index')
def room(request, room_name):
messages = Message.objects.filter(room = room_name)[:25:]
return render(request, 'chatroom.html', {
'room_name': room_name,
'messages': messages
})
Here is the part that should display the messages in chatroom.html template:
<div class="container_chat">
<form>
<div class="textarea" id="chat-text" rows="10" readonly> </div>
<div class=container_chat_inputs>
<input id="input" placeholder="Enter a message" type="text"></br>
<input class="chat_message_submit" id="submit" type="button" value="Send">
</div>
</form>
</div>
And here is my function for saving the messages in the model in consumers :
@sync_to_async
def save_message(self, username, room, message):
Message.objects.create(username = username, room = room, content = message)
So far I believe that the main problem is in the filtering in views. Right now it only seems to display the first 25 messages. I tried reversing the slice, but Django does not support negative slicing. I also tried reversing the ordering, which does display the last 25 messages, but of course in a reversed order.
Question: How do I fix this? How do I display the last 25 messages?
Aucun commentaire:
Enregistrer un commentaire