I am making a chat box for my website. As per current implementation,i i am iterating over the current friends list and and anchor tag triggers a modal for that particular user. The modal is common for all users as it only changes the data inside. Now, i have used jquery to fetch the message history ( from model object ) and display is modal body. I can click on different users and view the messages in their respective models correctly. However, when i try to submit the form to send another message it gets added to the message box of first user. This is happening for all users in the friend list.

How can i trigger the form to post in the model of the correct user.


{% for friend in friends_list %}
                <a href=""  data-toggle="modal" data-target="#chatbox" data-whatever="{{friend.to_user}}"><li style="padding:10px">{{friend.to_user.usercreation.fname}}  {{friend.to_user.usercreation.lname}} <i style ="color:green;font-size:0.65rem;text-align:justify;float:right;margin-top:8.5px;" class="fa fa-circle" aria-hidden="true"></i></li></a>
                <form  action="{% url 'usercreation:addmessage' friend.to_user.usercreation.pk %}" method="post">
                    {% csrf_token %}
                <div class="modal fade" id="chatbox" tabindex="-1" role="dialog">
                  <div class="modal-dialog" role="document">
                    <div class="modal-content">
                      <div class="modal-header text-center">
                        <h6 class="modal-title w-100">BlogChat</h6>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                          <span aria-hidden="true">&times;</span>
                    <pre><div class="modal-body"></div></pre>
                          <div class="modal-footer">
                            <input style="width:330px;height:40px" type="text" name="addmessage" value="" placeholder="Type..">
                            <button style="float:right;" type="submit" class="btn btn-primary">Send message</button>
            {% endfor %}


<script type="text/javascript">
$('#chatbox').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) 
var recipient = button.data('whatever') 
     url: "{% url 'fetcher' %}",
     data: {
    'search': recipient
      dataType: 'json',
      success: function (data) {
       list = data.list;

       var modal = $(this)
       modal.find('.modal-title').text('Chat with ' + recipient)



def fetcher(request):
if request.is_ajax():
    name = User.objects.get(username=request.GET.get('search', None))
    b = ChatMessage.objects.get(user1 = request.user,user2 = name)
    data = {
        'list': b.message,
    return JsonResponse(data)

def addmessage(request,pk):
if request.method=='POST':
    obj = ChatMessage.objects.get(user1 = request.user , user2 = User.objects.get(username=UserCreation.objects.get(pk=pk)) )
    obj2 = ChatMessage.objects.get(user2 = request.user , user1 = User.objects.get(username=UserCreation.objects.get(pk=pk)) )
    name = request.POST.get('addmessage')

    obj.message += ('\n'+str(request.user)+': '+name)
    obj2.message += ('\n'+str(request.user)+': '+name)
return HttpResponseRedirect(reverse('usercreation:profile',args=[request.user.usercreation.pk]))


class ChatMessage(models.Model):
user1 = models.ForeignKey(User, on_delete=models.CASCADE ,related_name="participant1")
user2 = models.ForeignKey(User, on_delete=models.CASCADE , related_name="participant2")
message = models.TextField(default="")
date = models.DateTimeField(auto_now=True, db_index=True)

0 Answers