首页 > 解决方案 > ajax 中缺少 csrf 令牌

问题描述

我正在尝试构建一个 ajax 驱动的类似按钮,但 ajax 代码不起作用。

views.py
def like_button(request,postid):
    postresult=get_object_or_404(post,id=postid)
    if postresult.user_like.filter(id=request.user.id).exists():
        postresult.user_like.remove(request.user)
    else:
        postresult.user_like.add(request.user)
    noresdat=postresult.totallikes
    response_data_to_dump={'success': True,'likes':noresdat}
    data = json.dumps(response_data_to_dump)
    return HttpResponse(data, content_type='application/json')

而模板如下:-

{% for p in result %}
    <div class="SpriteContainer"> 
      <a class="postlike" href="/like/{{ p.id }}"><img src="{%static "/images/icons/heart.png" %}"/></a>
      <p class="nolike" style="display: inline-block;">{{ p.totallikes }}</p></div>
    {% endfor %}
<script>
    var csrftoken = $("[name=csrfmiddlewaretoken]").val();
    $(".postlike").click(function(e){
      e.preventDefault();
      var $this = $(this);
      var url = $(this).data("action");
      $.post(url, function(response){
      if(response && response.success==true)
      $this.next(".nolike").text(response.likes);
  });
});

标签: pythonajaxdjangodjango-views

解决方案


CSRF 中间件和模板标签提供了针对跨站点请求伪造的易于使用的保护。(Django)。

并且在 MIDDLEWARE 设置中默认激活 CSRF 中间件。所以要么你必须提供 csrf 令牌,要么你必须从 CSRF 中排除该视图。视图基于类或函数。由于您使用的是基于函数的视图,因此您可以利用 [csrf_exempt]。1

from django.views.decorators.csrf import csrf_exempt,
    @csrf_exempt
    def like_button(request,postid):

推荐阅读