You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django模板标签问题:实现用户删除自有评论的功能

Fixing Your Django Comment Delete Visibility Issue

Hey there! Let's get that delete comment link working correctly for only the comment's author. I noticed two key issues in your template code that are preventing this from working as expected:

  • Typos break the condition: You have a typo in your ifequal tag—commment.user has an extra 'm' (it should be comment.user). This typo means Django can't resolve the variable correctly, so the condition will never evaluate to true.
  • Mismatched comparison types: comment.user is a full User model instance, while user.username is just a string. Comparing these two directly will never return true, even for the correct user. You have two solid ways to fix this:
    1. Compare the username strings: Use comment.user.username to get the string username from the comment's author, then compare it to user.username.
    2. Compare User instances directly (recommended): Since Django User objects can be compared directly to check if they're the same user, you can use a regular if tag instead of ifequal for cleaner code: {% if comment.user == user %}

Here's the corrected version of your template code using the recommended instance comparison:

<div class="comment">
  <h2 class="commenter">{{ comment.user }}</h2>
  <p class="commentdate">{{ comment.created }}</p>
  <p class="commentbody">{{ comment.body }}</p>
  "{{ comment.user }}" "{{ user.username }}"
  {% if comment.user == user %}
    <p><a href="#">Delete comment</a></p>
  {% endif %}
</div>

A quick note: If you still want to use ifequal, the corrected line would be {% ifequal comment.user.username user.username %}, but using the direct instance comparison is more robust (it avoids edge cases where two users might have the same username, though that's unlikely if your auth system is set up properly).

Give this a try, and your delete link should only show up for the user who posted the comment!

内容的提问来源于stack exchange,提问作者Danny

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:26:12