post方式不同于get方式可以被django直接得到,因为django为post加入了csrf保护, 详细的文档地址https://docs.djangoproject.com/en/dev/ref/csrf/
注释:在最新版本中,在setting.py里'django.middleware.csrf.CsrfViewMiddleware',默认是使用中的,如果没有请自行添加,并且确保此引用在其他所有viewware前面
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',//this line is vsrf
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django_cas.middleware.CASMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
如果想避过csrf检测这一层直接使用post的话,有几种方法:
1 需要在views.py里要出发post请求的函数前加入@csrf_exempt ,之前要引入from django.views.decorators.csrf import csrf_exempt
2 在 settings.py 中 MIDDLEWARE_CLASSES 中 注释掉'django.middleware.csrf.CsrfViewMiddleware'
说下正确使用csrf的方法 :
对于ajax.post方法,需要在ajax方法触发前加入一段js,这段我理解是用来生成不同的token,但是很好奇如果禁掉了cookie会怎样我没研究.
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;
}
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
ajax方法 :
$.ajax({
url: "ticket/operation/?action=get_vmlist",
data: { 'env': env, 'subenv': subenv },
type: "post",
dataType: 'json',
beforeSend: function (xhr, settings) {
//此处调用刚刚加入的js方法
var csrftoken = getCookie('csrftoken');
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
},
success: function (data) {
},
complete: function () {
},
error: function (er) {
}
});
view.py:
def ticket_handler(request):
if request.method == 'POST':
if request.GET['action'] == 'get_vmlist':
try:
d = {}
env = request.POST['env']
print env //这里就可以看到env的值被正确传递给后台了
d['Result'] = 'Fail'
s = json.dumps(d)
return HttpResponse(s)
btw:
可以显示对单个view函数进行csrf保护,
from django.views.decorators.csrf import csrf_protect
@csrf_protect
def my_view(request):
c = {}
# ...
return render(request, "a_template.html", c)