繁体   English   中英

Django Ajax表单提交指向403 Forbidden

[英]Django Ajax form submission pointing to a 403 Forbidden

我允许用户通过ajax删除帖子。 帖子有一个布尔字段live_until_removed。 设置为false时,帖子会消失。

点击删除我给了403,引用:

xhr.send( ( s.hasContent && s.data ) || null );

如何让它顺利运行? 为什么会发生这种错误?

JS:

$('#removeForm').submit(function() { // catch the form's submit event
    $.ajax({
        data: $(this).serialize(),
        type: $(this).attr('method'), 
        url: $(this).attr('action'),
        success: function(response) {
            $('.close-post').html(response); // update the DIV
            console.log(response);
        },
        error: function(response){
            console.log(response);
        }
    });
    return false;
});

模板:

<div class="close-post">
     {% if not post.live_until_removed %}
     <form class="" id="removeForm" method="POST" action="">
          <button type="submit" class="btn">Remove</button>
     </form>
     {% else %}
     <button class="btn">Removed</button>
     {% endif %}
</div>

views.py:

def post(request, id):
    ...
     if request.is_ajax():
          try: 
               post = Post.objects.get(id=id)
               post.live_until_removed = False
               post.save()
               response = simplejson.dumps({"status": "Removed"})
          except:
               pass

您可能错过了在请求中发送CSRF令牌。 看看这里; Django的阿贾克斯

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM