Метод не разрешен (POST) в ajax-запросе с помощью django

Я пытаюсь передать значения данных формы через ajax .И получаю ошибку method not allowed. Я пытаюсь добавить комментарий к записи в блоге.

Это моя форма, которая находится на странице blog_detail

            <form id="commentform" class="commentform" method="post">
            
            {% csrf_token %}

            {%with allcomments.count as total_comments%}
            <p>
              {{total_comments}} comment{{total_comments|pluralize}}

            </p>
            {%endwith%}
            <select name="blog" class="d-none" id="id_blog">
              <option value="{{blog.id}}" selected="{{blog.id}}"></option>
            </select>
            <label class="small font-weight-bold">{{comment_form.parent.label}}</label>
            {{comment_form.parent}}
            <div class="d-flex">
              <img class="avatar_comment align-self-center" src="{% for data in avatar%}{{data.avatar.url}}{%endfor%}" alt="">
              {{comment_form.content}}
            </div>
            <div class="d-flex flex-row-reverse">
              <button value="commentform" id="newcomment" type="submit" class="newcomment btn btn-primary">Submit</button>

            </div>
          </form>

И когда я нажимаю на кнопку, она должна вызвать ajax

   $(document).on('click','#newcomment',function(e){
              e.preventDefault();
              var button =$(this).attr("value");

              var placement = "commentform"
              if (button=="newcommentform"){
                var placement = "newcommentform"
              }

              $.ajax({
                type: 'POST',
                url: '{% url "website:addcomment"  %}',
                data: $("#" + button).serialize(),
                cache: false,
                sucess: function(json){
                  console.log(json)

                   $('<div id="" class="my-2 p-2" style="border: 1px solid grey"> \
                  <div class="d-flex justify-content-between">By ' + json['user'] + '<div></div>Posted: Just now!</div> \
                  <div>' + json['result'] + '</div> \
                  <hr> \
                  </div>').insertBefore('#' + placement);
                },
                error: function(xhr,errmsg,err){

                }
              });
            })

Это мой urls.py

path('blog/<int:blog_id>', BlogDetails.as_view(), name="blog_detail"),
path('addcomment/',addcomment, name="addcomment"),

и мой views.py имеет следующий вид:

class BlogDetails(View):
    def get(self, request, blog_id):
        query = request.GET.get('query')
        if query:
            return redirect(reverse('website:search') + '?query=' + query)

        blog = Blog.objects.get(id=blog_id)
        total_comment = Comment.objects.filter(blog=blog).count()
        allcomments = blog.comments.filter(status=True)
        blog_list = Blog.objects.all()
        comment_form = NewCommentForm()
        data = {
            'blog': blog,
            'blog_list': blog_list,
            'total_comment': total_comment,
            'comment_form': comment_form,
            'allcomments': allcomments
        }
        return render(request, "blog_detail.html", data)


   

    def addcomment(request):
       if request.method == 'post':
          comment_form = NewCommentForm(request.POST)
          print(comment_form)
          if comment_form.is_valid():
             user_comment = comment_form.save(commit=False)
             user_comment.user = request.user
             user_comment.save()
             result = comment_form.cleaned_data.get('content')
             user = request.user.username
             return JsonResponse({'result': result, 'user': user})

Пожалуйста, помогите мне с этим, он не вызывает представление addcomment

Если то, как я интерпретировал ваш код, верно, то, вероятно, он будет работать, если изменить ваш класс BlogDetails на такой:

class BlogDetails(View):
    def get(self, request, blog_id):
        query = request.GET.get('query')
        if query:
            return redirect(reverse('website:search') + '?query=' + query)

        blog = Blog.objects.get(id=blog_id)
        total_comment = Comment.objects.filter(blog=blog).count()
        allcomments = blog.comments.filter(status=True)
        blog_list = Blog.objects.all()
        comment_form = NewCommentForm()
        data = {
            'blog': blog,
            'blog_list': blog_list,
            'total_comment': total_comment,
            'comment_form': comment_form,
            'allcomments': allcomments
        }
        return render(request, "blog_detail.html", data)


    def post(self, request, *args, **kwargs):
        return self.addcomment(request)

    def addcomment(self, request):
        comment_form = NewCommentForm(request.POST)
        print(comment_form)
        if comment_form.is_valid():
           user_comment = comment_form.save(commit=False)
           user_comment.user = request.user
           user_comment.save()
           result = comment_form.cleaned_data.get('content')
           user = request.user.username
           return JsonResponse({'result': result, 'user': user})

Потому что вы пытаетесь POST к представлению, у которого не определен метод post.

Тогда вам нужно убрать addcomment из URL, к которому вы обращаетесь, и просто отправить сообщение на тот URL, на котором вы сейчас находитесь.

Вернуться на верх