簡體   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