Django 表单注释总是返回 GET 请求,POST 请求 'Method Not Allowed'

Django form comment always returning GET requests, POST request 'Method Not Allowed'

我正在尝试实现登录用户可以在博客上发表评论的功能 post,但我对页面上显示的评论有些困惑。

我可以输入评论并提交。但是,这总是返回一个 GET 请求。我尝试将 method='post' 添加到表单和按钮标签,但这导致了以下结果:

Method Not Allowed (POST): /post/1/
Method Not Allowed: /post/1/

我不太确定问题出在哪里。任何帮助将非常感激。下面的代码片段。

post_detail.html 评论区:

   <div class="content-section">

    <legend class="border-bottom">Comments:</legend>

    {% if user.is_authenticated %}
      
      <form id="commentForm">
        {% csrf_token %}
        <fieldset class="form-group">
          <div class="row">
            <!-- <div class="col"></div> -->
            <div class="col-1 text-right">
              <img class="img-comment" src="{{ user.profile.image.url }}">
            </div>
            <div class="col-9">
              <textarea type="text" id="commentIn" name="comment" 
               placeholder="Your comment..." required></textarea> 
            </div>
            <div class="col"></div>
          </div>
          <div class="row">
            <div class="col-10 text-right">
              <button id="commentBtn" name="comment_button" 
                      class="btn btn-outline-info" type="submit">Comment</button>
            </div>
            <div class="col"></div>
          </div>
          <hr>
        </fieldset>
      </form>
    {% endif %}

    
    <div id="commentDiv">
      {% for cmnt in comments_list %}
        <img class="img-comment" 
        src="{{cmnt.commentator.profile.image.url }}">
        <a class="mr-2" >{{ cmnt.commentator }}</a>
        <p class="article-content">{{ cmnt.comment }}</p>
      <hr>
      {% endfor %}
    </div>

  </div>

urls.py 在博客应用中

urlpatterns = [
    path('post/<int:pk>/', PostDetailView.as_view(), name="post-detail"),

models.py

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    likes = models.ManyToManyField(User, related_name='like')
    
    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('post-detail', kwargs={'pk': self.pk})


class Comment(models.Model):
    commentator = models.ForeignKey(User, on_delete=models.CASCADE)
    blog = models.ForeignKey(Post, on_delete=models.CASCADE)
    comment = models.CharField(max_length=200)
    date_added = models.DateTimeField(default=timezone.now)

    class meta:
        verbose_name_plural = 'comments'

    def __str__(self):
        return self.comment

views.py

class PostDetailView(DetailView):
    model = Post
    form = CommentForm()

    def get_context_data(self, **kwargs):

        if self.request.method == 'GET':
            print('Render a blank form for users to fill out')
            print(self.form)

        elif self.request.method == 'POST':
            print('Get the data from the POST request')
            print(self.form)

        status = 0
        if self.request.user in self.object.likes.all():
            status = 1
        context = super().get_context_data(**kwargs)
        context['comments_list'] = Comment.objects.filter(blog=self.object)
        context['status'] = status
        return context

最后,表格本身:

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ['comment']

不要将 class-based-view 与 method-based-view 混用。您必须提供读取方法并按其应有的方式运行的功能。对于 get,您通常会有 built-in 个解决方案,例如 form_class - 在 post() 中,您可以通过 form = self.get_form() 调用它。它通常看起来像这样:

class PostDetailView(DetailView):
    model = Post
    form_class = CommentForm

    def post(self, request, *args, **kwargs):
        form = self.get_form()
        print('Get the data from the POST request')
        print(form)

    def get_context_data(self, **kwargs):
        status = 0
        if self.request.user in self.object.likes.all():
            status = 1
        context = super().get_context_data(**kwargs)
        context['comments_list'] = Comment.objects.filter(blog=self.object)
        context['status'] = status
        return context

要检查的另一件事,即。这里: