python - 指向 403 Forbidden 的 Django Ajax 表单提交

标签 python ajax django jquery

我允许用户通过 ajax 删除帖子。帖子有一个 bool 字段 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 token 。看这里; Django-Ajax

关于python - 指向 403 Forbidden 的 Django Ajax 表单提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16223834/

相关文章:

python - 将 Django 的模板引擎移植到 C

python - 根据字符串属性索引拆分 Pandas 数据框

java - 在 Java 代理中访问 POST 数据

python - Django 中的 MultiValueDictKeyError

python - 如何在 python 中实现 makefile 风格的算法

python - 将 NaN 添加到 pandas 系列时,保留 bool 和 float 之间的区别?

javascript - 我想要 .fadeout 每个 div 期望 .this

php - 加载太多图片,减慢我的网站

python - 如何在 Python 中考虑正则表达式的重音字符?

python - 如果mysql数据库驻留在wamp服务器上,如何将django项目连接到mysql数据库?