我正在尝试为帖子中当前用户的单个评论添加删除按钮。我在我的 views.py 中尝试了下面的功能,但它返回错误:找不到页面(404) 请求方式:GET 请求网址:http://127.0.0.1:8000/comments/15/delete/ 提出者:feed.views.comment_delete
知道我做错了什么吗?
views.py
@login_required
def comment_delete(request, pk):
comment = get_object_or_404(Comments, pk=pk)
if request.user.id == comment.username_id:
Comments.objects.get(pk=pk).delete()
messages.error(request, f'Comment Deleted')
return redirect('post-detail', pk=pk)
models.py
class Post(models.Model):
description = models.TextField(max_length=255)
pic = models.ImageField(upload_to='path/to/img', blank=True)
date_posted = models.DateTimeField(default=timezone.now)
user_name = models.ForeignKey(User, on_delete=models.CASCADE)
tags = models.CharField(max_length=100, blank=True)
def __str__(self):
return self.description
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk': self.pk})
class Comments(models.Model):
post = models.ForeignKey(Post, related_name='details', on_delete=models.CASCADE)
username = models.ForeignKey(User, related_name='details', on_delete=models.CASCADE)
comment = models.CharField(max_length=255)
comment_date = models.DateTimeField(default=timezone.now)
post_detail.html
<h4 class="comment_text">Comments</h4>
<div class="row">
<div class="col-xl-9 col-md-10 m-auto order-xl-2 mb-0 mb-xl-0">
{% if post.details.all %}
<div class="card card-signin my-0">
{% for detail in post.details.all %}
<div class="card-body">
<a href="{{ detail.username.profile.get_absolute_url }}">
<img src="{{ detail.username.profile.image.url }}" class="rounded-circle" width="30" height="30" alt="">
</a>
<a class="text-dark" href="{{ detail.username.profile.get_absolute_url }}"><b>{{ detail.username }}</b></a>
<a class="comment_delete" href="{% url "comment-delete" user.id %}">delete</a>
<br><small>{{ detail.comment_date }}</small><br><br>
<p class="card-text text-dark">{{ detail.comment }}</p>
</div>
<hr class="my-1">
{% endfor %}
</div>
{% else %}
<p>No comments to show!</p>
{% endif %}
</div>
答案 0 :(得分:1)
在你的模板中你写了 {% url "comment-delete" user.id %}
,而实际上视图期望的参数是 comments id/pk。将其更改为 {% url "comment-delete" detail.pk %}