我试图允许用户按提交,并为此创建另一个评论,但是单击帖子时会收到“不允许使用方法(POST):”。
class PostDetailView(DetailView):
model = Post
def get_context_data(self, **kwargs):
# post = Post.objects.filter(id = self.kwargs['pk'])
post = get_object_or_404(Post, id=self.kwargs['pk'])
comments = Comment.objects.filter(post=post).order_by('-id')
is_liked = False
if post.likes.filter(id=self.request.user.id).exists():
is_liked = True
context = super().get_context_data(**kwargs)
if self.request.method == 'POST':
comment_form = CommentForm(self.request.POST or None)
if comment_form.is_valid():
content = self.request.POST.get('content')
comment = Comment.objects.create(post=post, user=self.request.user, content=content)
comment.save()
return HttpResponseRedirect(post.get_absolute_url())
else:
comment_form = CommentForm()
context['is_liked'] = is_liked
context['total_likes'] = post.total_likes()
context['comments'] = comments
context['comment_form'] = comment_form
return context
以及模板:
<form method="post">
{% csrf_token %}
{{ comment_form.as_p}}
<input type="submit" value="Submit" class="btn btn-outline-success">