我希望用户能够删除他们写的评论。不幸的是,我无法让 if 语句发挥作用。
{% if comment.name == user %}
<a href="{% url 'delete_own_comment' comment.id %}">delete this comment-</a>
{% endif %}
所以我可以看到 user 和 comment.name 的值,我包含了以下代码。这是出于测试目的,不会包含在站点的最终设计中。
<h3 class="article-content">{{ user }}</h3>
<p class="article-content">{{ comment.name }}</p>
我还想进行测试以确保 if 语句的内部正常工作。
<a href="{% url 'delete_own_comment' comment.id %}">delete this comment-</a>
{% endif %}
所以我添加了以下代码。同样,这不会包含在我的最终网站设计中。
{% if post.author == user %}
<a href="{% url 'delete_own_comment' comment.id %}">-------delete this comment---------</a>
{% endif %}
但通过查看屏幕截图,您可以看出代码无法正常工作。第 30 条评论是“用于 StackOverflow 目的的测试评论”。该评论由罗斯西蒙兹撰写。当前登录的用户是 RossSymonds。如果一切正常,您将看到“删除此评论”(与“--------删除此评论 ---------”不同)。
有人有建议吗?
{% extends "blog/base.html" %}
{% block content %}
{% load crispy_forms_tags %}
<article class="media content-section">
<img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2" href="#">{{ post.author }}</a>
<small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small>
{% if post.author == user %}
<div>
<a class="btn btn-secondary btn-sm mt-1 mb-1" href="{% url 'post-update' post.id %}">Update</a>
<a class="btn btn-danger btn-sm mt-1 mb-1" href="{% url 'post-delete' post.id %}">Delete</a>
</div>
{% endif %}
</div>
<h2 class="article-title">{{ post.title }}</h2>
<p class="article-content">{{ post.content }}</p>
</div>
</article>
<article class="media content-section">
<!-- comments -->
<h3>{{ comments.count }} Comments</h3>
</article>
<!-- comments -->
{% for comment in comments %}
<article class="media content-section">
<div class="media-body">
<small class="text-muted">{{ comment.id}}</small>
<small class="text-muted">{{ comment.name}}</small>
<small class="text-muted">{{ comment.created_on|date:"F d, Y" }}</small>
<div class="media-body ">
<p class="article-content">{{ comment.body }}</p>
<h3 class="article-content">{{ user }}</h3>
<p class="article-content">{{ comment.name }}</p>
</div>
</div>
{% if comment.name == user %}
<a href="{% url 'delete_own_comment' comment.id %}">delete this comment-</a>
{% endif %}
{% if post.author == user %}
<a href="{% url 'delete_own_comment' comment.id %}">-------delete this comment---------</a>
{% endif %}
</article>
{% endfor %}
{% if user.is_authenticated %}
<form action="" method="post">
{% csrf_token %}
{{ comment_form|crispy }}
<input type="submit" value="Submit">
</form>
{% else %}
<article class="media content-section">
Users who are logged in can post comments.
</article>
{% endif %}
{% endblock content %}