首页 > 解决方案 > Python Django - 模板标签中的 {% request.user.is_authenticated %} 不适用于 JS

问题描述

我正在博客中开发评论/回复系统。如果评论有任何回复,则显示为 1 条回复等,单击链接将打开回复。

<a class="comment-reply-btn" href="#" > Reply </a>

单击回复会切换包含回复的 div,否则使用 css 将其隐藏。

div是: -

<div class="comment-reply ml-5 mt-1">
{% for child_comment in comment.children %}
<img class="rounded-circle" alt="{{child_comment.user.get_full_name }}" src="{{child_comment.user.userprofile.get_user_image}}" height="18px" width="18px">
<h6 class="d-inline ml-3">{{ child_comment.user.get_full_name }}: </h6>
<span>{{ child_comment.content }}</span>
<footer>{{ child_comment.timestamp|timesince }} ago</footer>
{% endfor %}
{% if request.user.is_authenticated %}
<form method="POST" action="."> {% csrf_token %}
{{ comment_form|crispy }}
<input type='hidden' name='parent_pk' value='{{ comment.pk }}'>
<input type='submit' value='Reply' class='btn btn-default'>
</form>
{% else %}
<p>You must login to reply</p>
{% endif %}
</div>

我正在使用以下 css 设置来隐藏 div 以防止在页面加载时显示:-

.comment-reply{
    display: none;
}

和下面的 js 在点击回复按钮时打开它

$(".comment-reply-btn").click(function(event){
        event.preventDefault();
        $(this).parent().next(".comment-reply").fadeToggle();
})

我的问题是,如果我已登录,它会打开回复和写新回复的表格。但是如果我没有登录,点击回复按钮不会打开回复(它应该)。

请帮忙。

标签: javascripthtmlcssdjangodjango-templates

解决方案


您必须使用 js 来处理每种情况的显示内容。首先在js中为其定义全局变量:

var user_is_authenticated = {{ request.user.is_authenticated|yesno:"true,false" }};

您可以使用该变量来处理代码。像这样的东西:

if (user_is_authenticated === true) {
    // append comments html code to your section
  }
else {
    // don't show the comments
  }


推荐阅读