How can I display in the chat list those with whom I corresponded earlier?

I have a chat code in which I want to display and suggest only those users with whom there has already been a correspondence, that is, both incoming and outgoing messages, and not all registered users

html code:

<div class="container" style="height: 75%;">
    <div class="card bg-dark h-100 border-light">
        <div class="card-body h-100">
            <div class="row h-100">
                <div class="col-md-4 border-right h-100">
                    <div class="list-group bg-dark" id='user-list'>
                        {% for u in users %} {% if not u.id == 1 and not u.id == user.id %}
                        <a class="list-group-item {% if u.id != chat_id %}bg-dark{% else %}bg-primary{% endif %} text-white" href="{% url 'chat-home' %}?u={{u.id}}">
                            <div>
                                <p>{{u.first_name}} {{u.last_name}} ({{u.username}})</p>
                            </div>
                        </a>
                        {% endif %} {% endfor %}
                    </div>
                </div>
                <div class="col-md-8 h-100">
                    {% if not chat_id > 0 %}
                    <div class="h-100 d-flex flex-column justify-content-center align-items-center">
                        <h3>Начните общение!</h3>
                        <p><small class="text-muted">Выберете человека, чтобы написать ему.</small></p>
                    </div>
                    {% else%}
                    <div id="chat-box-field" class="h-100">
                        <div class="chat-box" style="height:80%">
                            {% for chat in chats %} {% if chat.user_from == user %}
                            <div class="p-2 w-100 d-flex justify-content-end">
                                <div class=" chat-bubble  ml-2 mb-2 bg-primary text-light rounded" data-id="{{chat.id}}">
                                    <p>{{chat.message}}</p>
                                    <div class="d-flex justify-content-between"><small>Ты</small> <small>{{chat.date_created|date:"M-d-Y H:i"}}</small></div>
                                </div>
                            </div>
                            {% else %}
                            <div class="p-2 w-100 d-flex justify-content-start">
                                <div class="chat-bubble mr-2 mb-2 bg-light text-dark rounded" data-id="{{chat.id}}">
                                    <p>{{chat.message}}</p>
                                    <div class=" d-flex justify-content-between"><small>От</small> <small>{{chat.date_created|date:"M-d-Y H:i"}}</small></div>
                                </div>
                            </div>
                            {% endif %} {% endfor %}
                        </div>
                        <div class="chat-box-form border-top p-2" style="height:20%">
                            <div class="w-100 h-100">
                                <form action="" id="chat-submit" class="h-100 d-flex ">
                                    <input type="hidden" name="user_from" value="{{ user.id }}">
                                    <input type="hidden" name="user_to" value="{{ chat_id }}">
                                    <div class="col-md-10 h-100">
                                        <textarea name="message" id="" class="h-100 w-100 form-control" placeholder="Написать"></textarea>
                                    </div>
                                    <button class="button btn btn-primary h-100 w-100 justify-content-center align-items-center d-flex">Отправить</button>
                                </form>
                            </div>
                        </div>
                    </div>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>
</div>

views.py:

def get_messages(request):
    chats = chatMessages.objects.filter(Q(id__gt=request.POST['last_id']),Q(user_from=request.user.id, user_to=request.POST['chat_id']) | Q(user_from=request.POST['chat_id'], user_to=request.user.id))
    new_msgs = []
    for chat in list(chats):
        data = {}
        data['id'] = chat.id
        data['user_from'] = chat.user_from.id
        data['user_to'] = chat.user_to.id
        data['message'] = chat.message
        data['date_created'] = chat.date_created.strftime("%b-%d-%Y %H:%M")
        print(data)
        new_msgs.append(data)
    return HttpResponse(json.dumps(new_msgs), content_type="application/json")

def send_chat(request):
    resp = {}
    User = get_user_model()
    if request.method == 'POST':
        post =request.POST
        
        u_from = UserModel.objects.get(id=post['user_from'])
        u_to = UserModel.objects.get(id=post['user_to'])
        insert = chatMessages(user_from=u_from,user_to=u_to,message=post['message'])
        try:
            insert.save()
            resp['status'] = 'success'
        except Exception as ex:
            resp['status'] = 'failed'
            resp['mesg'] = ex
    else:
        resp['status'] = 'failed'

    return HttpResponse(json.dumps(resp), content_type="application/json")

models.py:

class chatMessages(models.Model):
    user_from = models.ForeignKey(User,
        on_delete=models.CASCADE,related_name="+")
    user_to = models.ForeignKey(User,
        on_delete=models.CASCADE,related_name="+")
    message = models.TextField()
    date_created = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return self.message

my chat

please tell me how it can be implemented. I don't quite understand how to set a condition for checking for messages

You probably need to change the related name first on the model:

class chatMessages(models.Model):
    user_from = models.ForeignKey(User,
        on_delete=models.CASCADE,related_name="sent")
    user_to = models.ForeignKey(User,
        on_delete=models.CASCADE,related_name="received")
    message = models.TextField()
    date_created = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return self.message

And then to get all messages the user has received:

messages = request.user.received.all()

(Or User.objects.get(id=my_user_id).received.all())

To get all the users which the user has corresponded with, you can then do:

pk_list = messages.values(user_from__pk).distinct()
correspondents = get_user_model().objects.filter(pk__in=list(pk_list))

Sidenote:

In your views, you are getting the user model.

User = get_user_model()

But you don't do anything with it in this view:

def send_chat(request):
Back to Top