【问题标题】:Python Django - {% request.user.is_authenticated %} in template tag not working with JSPython Django - 模板标签中的 {% request.user.is_authenticated %} 不适用于 JS
【发布时间】:2019-01-19 03:25:12
【问题描述】:

我正在开发博客中的评论/回复系统。如果评论有任何回复,则显示为 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();
})

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

请帮忙。

【问题讨论】:

    标签: javascript html css django django-templates


    【解决方案1】:

    您必须使用 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
      }

    【讨论】:

    • 您好,我即将通过您的回答解决我的问题。我现在遇到的问题是我需要附加一个包含 {% csrf_token %} {{ comment_form|crispy }} 的表单,该表单在 html 中附加为 ` " {% csrf_token %} {{ comment_form|crispy }} " `
    • 您可以从浏览器 cookie 中获取 csrftoken 以填充 的隐藏输入值并将其附加到您想要的部分中。
    • 我发现相反。如果用户未通过身份验证,我将表单添加到 div 并使用 remove 而不是 append 将其删除。
    猜你喜欢
    • 2016-05-26
    • 2021-07-26
    • 2017-11-07
    • 2018-12-24
    • 2014-03-20
    • 1970-01-01
    • 1970-01-01
    • 2014-09-21
    • 1970-01-01
    相关资源
    最近更新 更多