我收到一个只在我的服务器上的生产模式下发生的CSRF_Token错误。但是,当我使用runserver命令从计算机终端运行它时,一切正常。我已阅读了许多与此有关的其他问题,但没有运气。看起来,我的情况与其他情况稍有不同,因为它在本地工作,但不在生产中。Django CSRF令牌只在生产中丢失
提交提交给views.py中的“submit”的Ajax表单时出现错误。有谁知道可能是什么原因造成的?另外,在Production模式下查看我的cookie,CSRF_Token甚至不在那里开始。本地它是。谢谢你的帮助。
这里是我的views.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
代码用于修饰阿贾克斯提交
$(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
}
})
};
解决方案是固定的这个问题。
“从django.views.decorators.csrf进口ensure_csrf_cookie”在views.py然后在查看上述“@ensure_csrf_cookie”返回包含ajax的形式
为什么不干脆把'{%csrf_token%}'到您的模板直接,而不是试图把它弄出来的饼干? –
那是我没有尝试过的一件事。生病报告回来。谢谢 –