weixin_33738578 2019-01-06 12:52 采纳率: 0%
浏览 61

AJAX中缺少CSRF令牌

I am trying to build a ajax powered like button, but the ajax code is not working.

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')

while template is as follows:-

{% 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);
  });
});

  • 写回答

2条回答 默认 最新

  • weixin_33736048 2019-01-06 13:06
    关注

    The CSRF middleware and template tag provides easy-to-use protection against Cross Site Request Forgeries.(Django).

    And The CSRF middleware is activated by default in the MIDDLEWARE setting. So either you will have to provide csrf token or you will have to exempt that view from CSRF. Views are based on classes or functions. Since you are using function based views, you can take advantage of [csrf_exempt].1

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

报告相同问题?