django 使用 ajax 调用后端有问题

问题描述

我是 Django 的新手。我想为我的博客文章创建喜欢的图标。这是我的 html 文件中的一个心形图标,我希望当我点击它时,它变成红色,然后在后端调用一个函数来更改数据库中的一个数字并将新数字发送回模板,全部使用 Ajax,在为了不喜欢帖子后刷新页面。我该怎么办,问题出在哪里?

在 html 文件中:

  <i class="fas fa-heart"></i>
  <b>{{ note.like }}</b>

脚本部分:

  <script>
    $(document).ready(function() {
        $('.fa-heart').click(function(e){
            this.style.color = this.style.color == 'red' ? 'white' : 'red';
            e.preventDefault();

                $.ajax({
                    type:'POST',url:"Vote/like/",data:{
                        num:"niloofar",//I think the problem is with this csrf token part
                        csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(),},success: function(data){
                        alert(data);
                    },error : function() {
                        console.log("Error");
                    }
                });
        });
    });
  </script>

在视图中:

  def like(request):
      if request.method == 'POST':
        print(request.POST)
        return HttpResponse('done')

在 urls.py 中:

  path('<int:id>/Vote/like/',views.like,name='like'),

错误是:

内部服务器错误:/notes/1/Vote/like/ Traceback(最近调用 最后):文件 "/home/niloofar/git/djangoenv/lib/python3.9/site-packages/django/core/handlers/exception.py",第 47 行,在内部 response = get_response(request) File "/home/niloofar/git/djangoenv/lib/python3.9/site-packages/django/core/handlers/base.py",第 181 行,在 _get_response 中 response = wrapper_callback(request,*callback_args,**callback_kwargs) TypeError: like() 得到一个意外的关键字参数 'id'

解决方法

/1/vote/like/ 的请求将匹配列表中的 URL <int:id>/vote/like/,Django 将调用函数 views.like(request,id=1) 但您的函数只接受单个参数 request 因此错误。

将您的函数 like 更改为如下所示的内容,然后它应该可以正常工作。

def like(request,id):
    ...

def like(request,*args,**kwargs):
    ...