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

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):
    
    评论

报告相同问题?

悬赏问题

  • ¥20 python忆阻器数字识别
  • ¥15 无法输出helloworld
  • ¥15 高通uboot 打印ubi init err 22
  • ¥20 PDF元数据中的XMP媒体管理属性
  • ¥15 R语言中lasso回归报错
  • ¥15 网站突然不能访问了,上午还好好的
  • ¥15 有没有dl可以帮弄”我去图书馆”秒选道具和积分
  • ¥15 semrush,SEO,内嵌网站,api
  • ¥15 Stata:为什么reghdfe后的因变量没有被发现识别啊
  • ¥15 振荡电路,ADS仿真