【发布时间】:2017-08-17 12:58:20
【问题描述】:
我收到一个丢失的 CSRF_Token 错误,该错误仅在我的服务器上的生产模式下发生。但是,当我使用 runserver 命令从计算机终端运行它时,一切正常。我已经阅读了许多与此有关的其他问题,但没有运气。看来我的情况与其他情况略有不同,因为它在本地有效,但在生产中无效。
我在提交提交到views.py 中的“提交”的Ajax 表单时收到错误消息。有人知道是什么原因造成的吗?此外,在生产模式下查看我的 cookie,CSRF_Token 甚至都不存在。本地是这样。谢谢你的帮助。
这是我的意见.py
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return render(request, 'index.html')
def submit(request):
#Receive Request
inputone = request.POST['randominfo']
inputtwo = request.POST['randominfo2']
#Some more code here that setups response.
#Deleted since Im posting to StackOverflow
return response
与 Ajax 提交有关的代码
$(function () {
$.ajaxSetup({
headers: { "X-CSRFToken": getCookie("csrftoken") }
});
});
function getCookie(c_name)
{
if (document.cookie.length > 0)
{
c_start = document.cookie.indexOf(c_name + "=");
if (c_start != -1)
{
c_start = c_start + c_name.length + 1;
c_end = document.cookie.indexOf(";", c_start);
if (c_end == -1) c_end = document.cookie.length;
return unescape(document.cookie.substring(c_start,c_end));
}
}
return "";
}
function submitAjax(event){
$.ajax({
type:'POST',
url:'/submit/',
data:{
randominfo:document.getElementById('Random').innerHTML,
randominfo2:document.getElementById('Random2').innerHTML,
},
dateType: 'json',
success:function() {
# Url here
}
})
};
解决此问题的解决方案。
在views.py中添加“from django.views.decorators.csrf import ensure_csrf_cookie”,然后在返回包含ajax表单的html文件的视图上方添加“@ensure_csrf_cookie”
【问题讨论】:
-
为什么不直接将
{% csrf_token %}放入您的模板而不是尝试从cookie 中取出它? -
那是我没试过的一件事。生病回来汇报。谢谢
标签: ajax django forms django-csrf