javascript - 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();
})
我的问题是,如果我已登录,它会打开回复和写新回复的表格。但是如果我没有登录,点击回复按钮不会打开回复(它应该)。
请帮忙。
解决方案
您必须使用 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
}
推荐阅读
- mysql - 如何在日期行中找到 00 并在 mysql 数据库中替换它?
- javascript - 动态设置“grid-template-areas”的问题
- python - python中的多处理池吐出总线10错误
- templates - 索引 Instantsearch.js 算法的不同结果模板
- tensorflow - Tensorflow - 无法为具有形状“(?,28,28,1)”的张量提供形状(256、784)的值
- node.js - SQL Server 中的 Sequlize upsert 失败
- forms - 通过会话传递数组并基于它获取信息
- android - 使用 UsbDeviceConnection.bulkTransfer 后如何从 USB 设备获得响应
- c# - 如何将 Unity 项目输入更新到 SteamVR 2.0?
- javascript - 将 IMG 对象附加到表格单元格中