我如何在 django 模板的 if 语句中使用 django 变量到 javascript 字符串变量

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

我想使用 javascript 变量将 div 添加到我的页面。这个 div 必须向右或向左取一个 class,但是我的 if 条件在这个变量中不起作用,如果我在没有 javascript 的情况下尝试它它会起作用。

这是我的看法:

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')

这是我的 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);
    });

这是我的 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']

我的js不太好所以我会用部分html来回答你的问题

  1. 在您的模板中创建一个 html 文件 (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(就是这个没有头)

{% 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. 打电话给你的 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);
     });
    

注意:这只是您如何使用 django 实现它的一个想法。