【问题标题】:django using ajax to call backend has problemdjango使用ajax调用后端有问题
【发布时间】:2021-06-16 15:34:44
【问题描述】:

我是 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(请求)文件“/home/niloofar/git/djangoenv/lib/python3.9/site-packages/django/core/handlers/base.py”, 第 181 行,在 _get_response 中 response = Wrapped_callback(request, *callback_args, **callback_kwargs) TypeError: like() got an unexpected keyword argument 'id'

【问题讨论】:

  • 您是否在您的urls.py 中设置了vote/like/ 端点?
  • @stackdon 是的。我已经更新了问题。

标签: javascript django ajax csrf-token


【解决方案1】:

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

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

def like(request, id):
    ...

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

【讨论】:

  • 哦,你是对的!为什么我没有注意到!谢谢。
猜你喜欢
  • 2011-09-22
  • 2021-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-31
  • 2017-01-04
  • 2014-06-24
  • 2011-08-28
相关资源
最近更新 更多