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

Time:08-28

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  style="height: 75%;">
    <div >
        <div >
            <div >
                <div >
                    <div  id='user-list'>
                        {% for u in users %} {% if not u.id == 1 and not u.id == user.id %}
                        <a  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 >
                    {% if not chat_id > 0 %}
                    <div >
                        <h3>Начните общение!</h3>
                        <p><small >Выберете человека, чтобы написать ему.</small></p>
                    </div>
                    {% else%}
                    <div id="chat-box-field" >
                        <div  style="height:80%">
                            {% for chat in chats %} {% if chat.user_from == user %}
                            <div >
                                <div  data-id="{{chat.id}}">
                                    <p>{{chat.message}}</p>
                                    <div ><small>Ты</small> <small>{{chat.date_created|date:"M-d-Y H:i"}}</small></div>
                                </div>
                            </div>
                            {% else %}
                            <div >
                                <div  data-id="{{chat.id}}">
                                    <p>{{chat.message}}</p>
                                    <div ><small>От</small> <small>{{chat.date_created|date:"M-d-Y H:i"}}</small></div>
                                </div>
                            </div>
                            {% endif %} {% endfor %}
                        </div>
                        <div  style="height:20%">
                            <div >
                                <form action="" id="chat-submit" >
                                    <input type="hidden" name="user_from" value="{{ user.id }}">
                                    <input type="hidden" name="user_to" value="{{ chat_id }}">
                                    <div >
                                        <textarea name="message" id=""  placeholder="Написать"></textarea>
                                    </div>
                                    <button >Отправить</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 messagesm

CodePudding user response:

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):
  • Related