How to filter private user to user interactions?

74 Views Asked by At

I'm creating a private user to user chat system, for now I'm displaying all of the objects through the views in the profile of the user like this user = userComment.objects.all().

The problem with that is that everyone can read everyone's chat messages and I would like to filter it so only the recipient and the sender can read the messages they send to each other.

If if filter it like so : userComment.objects.filter(sender=request.user) then only sended message will be shown.

If I filter it like that : userComment.objects.filter(recipient=request.user) then only received message will be shown.

I would like to filter it so only the recipient and the sender can read their chat.

Why do I want to filter it into one variable ? So it can look like this : enter image description here

And not like this :

enter image description here

models.py

class userChat(models.Model):
    sender = models.ForeignKey(User, related_name="sender")
    receiver = models.ForeignKey(User, blank=True, null=True, related_name="receiver")
    sent_at = models.DateTimeField(auto_now_add=True)
    comment = models.TextField(max_length=255, null=True)

    def __str__(self):
        return str(self.sent_at)

template/file.html

{% for user in users %}
    {% if user.client == request.user %}
            <li style="text-align:left; background:yellow;">
                <p>from {{ user.client }} to <strong>{{ user.worker }} </strong> | {{ user.sent_at }}</p>
                <p>{{ user.comment }}</p>
            </li>
        {% else %}
            <li style="text-align:right; background:#eaeaea;">
                <p>from {{ user.client }} to <strong>{{ user.worker }}</strong> | {{ user.sent_at }}</p>
                <p>{{ user.comment }}</p>
            </li>
        {% endif %}
{% endfor %}

Update : Following Daniel Roseman's example I've tried this :

filter(Q(recipient=request.user) | Q(sender=request.user)).order_by('sent_at')

The problem is that another user can still see the chat messages between the recipient and the sender.

1

There are 1 best solutions below

7
On BEST ANSWER

Use Q to do an OR query.

from django.db.models import Q
UserComment.objects.filter(Q(sender=request.user) | Q(receiver=request.user))