在我的Django应用程序中,我试图删除一个与帖子相关的评论,但我一直收到这个错误消息。预期的输出是要从站点和数据库中删除的注解。
异常类型:AttributeError异常值:
通用细节视图CommentDeleteView必须使用对象pk或URLconf中的slug调用。
我是Django的新手,我不知道如何解决这个错误。
urls.py:
from django.urls import path
from .views import CommentCreateView, CommentDeleteView
from . import views
urlpatterns = [
path('post/<int:pk>/comment', CommentCreateView.as_view(), name='add-comment'),
path('post/<int:post_pk>/comment_delete/<int:comment_pk>/', CommentDeleteView.as_view(), name='comment-delete'),
]
CommentDeleteView:
class CommentDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
model = Comment
template_name = 'blog/comment_delete.html'
context_object_name = 'comment'
def test_func(self):
comment = self.get_object()
return comment.author == self.request.user
def get_success_url(self):
return reverse('post-detail', kwargs={'pk': self.object.post.pk})
def get_object(self, queryset=None):
obj = super().get_object(queryset=queryset)
return get_object_or_404(Comment, pk=obj.pk)
评论型号:
class Comment(models.Model):
post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE)
author = models.ForeignKey(User, on_delete=models.CASCADE)
content = models.TextField()
date_posted = models.DateTimeField(default = timezone.now)
def __str__(self):
return self.content
“删除注解”按钮所在的Html模板:
{% for comment in post.comments.all %}
<article class="media content-section">
<div class="media-body">
<div class="article-metadata">
<small class="text-muted">Posted: {{ comment.date_posted|date:"H:i, j F, Y" }}</small>
{% if comment.author == user or post.author == user%}
<div>
<form method="post" action="{% url 'comment-delete' post_pk=post.pk comment_pk=comment.pk %}">
{% csrf_token %}
<button class="btn btn-danger btn-sm" type="submit">Delete Comment</button>
</form>
</div>
{% endif%}
</div>
<div class="article-content">
<a class="article-title" href="#">{{ comment.content }}</a>
</div>
</div>
</article>
{% endfor%}
我不知道如何处理这个问题。我希望评论被删除并被重定向到帖子页面。
1条答案
按热度按时间af7jpaap1#
get_object
应该返回comment_pk
的对象,其中post_id
和author
匹配,因此: