简体   繁体   中英

How I can use a django variable in if statement of django template into a javascript string variable

I want to add a div to my page using a javascript variable. This div must take a class right or left,but my if condition doesn't work in this variable, And it works if I try it without javascript.

This is my view:

def chat(request,sender_id,receiver_id):
    if request.user.is_authenticated:
        if request.user.profile == 'C' or request.user.profile == 'A':
            user = User.objects.filter(id=request.user.id).get()
            receiver_user = User.objects.filter(id=receiver_id).get()
            if request.user.profile == 'A':
                chat = Chat.objects.filter(Q(sender_id=sender_id) | Q(receiver_id=sender_id)).all()
            elif request.user.profile == 'C':
                chat = Chat.objects.filter(Q(sender_id=sender_id,receiver_id=receiver_id) | Q(sender_id=receiver_id,receiver_id=sender_id))

            context = {
                'user': user,
                'chat': chat,
                'receiver_user': receiver_user,
            }
            return render(request,'chat/chat.html',context)
    return render(request, 'Login/logout.html')

And this is my javascript:

$(document).ready(function(){
    
        setInterval(function(){
            $.ajax({
                type: 'GET',
                url : "{% url 'getMessages' request.user.id receiver_user.id %}",
                success: function(response){
                    console.log(response);
                    $("#display").empty();
                    for (var key in response.chat)
                    {
                        var temp='<div class="msg-box {% if request.user.id == chat.sender_id %} right {% else %} left {% endif %}">\
                            <div class="details">\
                                <p class="msg">'+response.chat[key].message+'</p>\
                                <p class="date">'+response.chat[key].msg_time+'</p></div></div>';
                        $("#display").append(temp);
                    }
                },
                error: function(response){
                    console.log('An error occured')
                }
            });
        },100);
    });

And this my models.py:

class Chat(models.Model):
    message = models.TextField(max_length=100000)
    sender = models.ForeignKey(User,on_delete=models.CASCADE,related_name='sender')
    receiver = models.ForeignKey(User,on_delete=models.CASCADE,related_name='receiver')
    msg_time = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['msg_time']

I am not so good in js so i will use partial html to answer your question.

  1. in your template create a html file (partial_msg.html):

     def getMessages(request, sender_id, receiver_id): if request.user.profile == 'A': chat = Chat.objects.filter(Q(sender_id=sender_id) | Q(receiver_id=sender_id)).all() elif request.user.profile == 'C': chat = Chat.objects.filter(Q(sender_id=sender_id,receiver_id=receiver_id) | Q(sender_id=receiver_id,receiver_id=sender_id)) return render(request,'partial_msg.html',{'chats':chat}) #new

2)partial_msg.html (just this without the head)

{% for chat in chats %}
<div class="msg-box {% if request.user.id == chat.sender_id %} right {% else %} left {% endif %}">
               <div class="details">
                <p class="msg">{{ chat.message }}</p>
                <p class="date">{{ chat.msg_time }}</p>
               </div>
</div>
{% endfor %}
  1. call your javascript

     $(document).ready(function(){ setInterval(function(){ $.ajax({ type: 'GET', url: "{% url 'getMessages' request.user.id receiver_user.id %}", success: function(response){ $("#display").empty(); $("#display").append(response); }, error: function(response){ console.log('An error occured') } }); },1000); });

Note: This is just an idea how you can achieve it using django.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM