Django模板标签问题:实现用户删除自有评论的功能
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
ifequaltag—commment.userhas an extra 'm' (it should becomment.user). This typo means Django can't resolve the variable correctly, so the condition will never evaluate to true. - Mismatched comparison types:
comment.useris a full User model instance, whileuser.usernameis just a string. Comparing these two directly will never return true, even for the correct user. You have two solid ways to fix this:- Compare the username strings: Use
comment.user.usernameto get the string username from the comment's author, then compare it touser.username. - 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
iftag instead ofifequalfor cleaner code:{% if comment.user == user %}
- Compare the username strings: Use
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

