JBull
JBull

Reputation: 43

Method Not Allowed (POST)

I'm trying to allow for the user to press the submit and for that to create another comment post but I receive "Method Not Allowed (POST): " when clicking 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

and for the template:

<form method="post">
{% csrf_token %}
{{ comment_form.as_p}}
<input type="submit" value="Submit" class="btn btn-outline-success">

Upvotes: 0

Views: 1257

Answers (1)

seuling
seuling

Reputation: 2966

As you can see here, you can't use POST method in DetailView. It only support get.

If you want to use POST, you should use formview or inherit formmixin.

Upvotes: 1

Related Questions