{csrf}token}给我403个禁止,而{%csrf}token%}给我500个服务器E

2024-09-28 04:21:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我读到这两个基本上是一样的东西,但每一个都给了我不同的错误,我不知道该找哪一个。我甚至不知道如何解决这个问题。有人能看一下我的代码吗,我已经为此挣扎了两天了。在

我的html

<div id='notificationsLoader'>
    </div>
<script>
$(document).ready(function(){
  $(".notification-toggle").click(function(e){
    e.preventDefault();
    $.ajax({
      type:"POST",
      url:"{% url 'get_notifications_ajax' %}",
      data: {
        csrfmiddlewaretoken:"{%csrf_token%}",
      },
      success: function(data){
        $("#notificationsLoader").html('<h3>notifications</h3>');
        $(data.notifications).each(function(){
          $("notificationsLoader").append(this + "<br/>")
        })
        console.log(data.notifications);
      },
      error: function(rs, e){
        console.log(rs);
        console.log(e);
      }


    })
  })
})
</script>

另一个html

^{pr2}$

通知来自我的python代码

@login_required
def get_notifications_ajax(request):
    notification = Notification.objects.get(id=id)
    notes =[]

    for note in notifications:
        notes.append(str(note))
    data={
        "notifications":notes
        }
    json_data = json.dumps(data)
    return HttpResponse(json_data, content_type='application/json')

这里还有更多内容,但是我只发布这一部分,因为我认为错误(403和500)表明我的服务器端是错误的


Tags: 代码divlogidjsondatagethtml
1条回答
网友
1楼 · 发布于 2024-09-28 04:21:02

来自Django Project Documenation

While the above method can be used for AJAX POST requests, it has some inconveniences: you have to remember to pass the CSRF token in as POST data with every POST request. For this reason, there is an alternative method: on each XMLHttpRequest, set a custom X-CSRFToken header to the value of the CSRF token. This is often easier, because many javascript frameworks provide hooks that allow headers to be set on every request.

因此,您可以将csrftoken值作为X-CSRFToken头传递,它可以从cookie中获取(我添加了getCookie函数以满足需要)。通过在发送ajax请求之前使用ajaxSetup设置ajax请求,可以很容易地做到这一点,请参见下面的代码:

// Source https://docs.djangoproject.com/en/1.7/ref/contrib/csrf/#ajax    
function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

$(".notification-toggle").click(function(e){
  e.preventDefault();
  var token = getCookie('csrftoken');
  $.ajaxSetup({'headers': {'X-CSRFToken': token}});
  // $.ajax... 

另外,您可以尝试从以下位置替换数据:

^{pr2}$

data: {
        csrfmiddlewaretoken:$("input[name=csrfmiddlewaretoken]").val()
      },

相关问题 更多 >

    热门问题