我在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令牌丢失或不正确?我如何找到或更正它?
答案 0 :(得分:0)
您没有在POST请求中包含CSRF令牌。
将您的代码更改为:
$.post("/searched-location",{typed_stuff: stuff_the_user_typed, csrfmiddlewaretoken: $("input[name=csrfmiddlewaretoken]").val()});
将其包含在您的请求中。