SO I have been trying to implement a basic one to one chat system in Django. So far, I have created a model that takes in two foreign keys( sender, recipient) and a Charfield by the name of message.
class message(models.Model):
sender=models.ForeignKey(User,related_name='sender2',on_delete=models.CASCADE)
receiver=models.ForeignKey(User,related_name='reciever2',on_delete=models.CASCADE)
message1=models.CharField(max_length=10000000)
Now, I am able to create message objects but what I want to do is display in a back-and forth conversation on one single page. I have so far been able to fetch all messages for a particular "sender-receiver" combination.
def view_message(request,pk):
client1=User.objects.get(id=pk)
client2=request.user
message1=message.objects.filter(sender=client1,receiver=client2).all()
return render(request,'message.html',{'messages':message1})
Now the above view just shows all messages for the single user who logged in, sent to the other user whose Primary key is being used/clicked on, But I also want to show are "replies" they receive in a conversation-style manner and in order. Hopefully, You guys understand what I am saying here. A one-to-one private messaging system (not asynchronous), so the page can refresh and reload all messages sent and received but in order. Thank you :)
You should add a date created field created_at = models.DateTimeField(auto_now_add=True)
to your model, due to how databases work PK is not going to be perfectly ordered (each connection might be given a chunk of PKs to use, this results in non perfect ordering, best is to use a timestamp)