CSRF令牌在`/`上从表单中丢失或不正确

时间:2018-01-11 02:15:25

标签: jquery python django csrf

我在urls.py

中有这个
url("^$", direct_to_template, {"template": "index.html"}, name="home"),
url("^searched-location", views.searched_location, name="searched_location"),

我在index.html

中有这个
{% extends "base.html" %}
{% load pages_tags mezzanine_tags i18n staticfiles %}

{% block main %}
<form id="my-form class="input-group">
    {% csrf_token %}
    <input type="text" class="form-control">
    <script src="{% static "script/script.js" %}"></script>
</form>
{% endblock %}

script.js有这一行:

document.getElementById("my-form").addEventListener("submit",function(event){
  event.preventDefault();
},false);

function when_User_Types_Something_Send_That_Stuff_To_The_Backend(typedStuff){
    // some code
    $.post("/searched-location",{typed_stuff: stuff_the_user_typed});
}

views.py有这个:

def searched_location(request):
    print request
    # More code here

问题是当我在本地运行python manage.py runserver时,我的终端出现此错误:

Forbidden (CSRF token missing or incorrect.): /searched-location
[11/Jan/2018 01:57:06] "POST /searched-location HTTP/1.1" 403 2502

为什么CSRF令牌丢失或不正确?我如何找到或更正它?

1 个答案:

答案 0 :(得分:0)

您没有在POST请求中包含CSRF令牌。

将您的代码更改为:

$.post("/searched-location",{typed_stuff: stuff_the_user_typed, csrfmiddlewaretoken: $("input[name=csrfmiddlewaretoken]").val()});

将其包含在您的请求中。