最近觉得SAE不错,就开始试试看,从Django开始.把原来MVC3的一个小项目转过来,记录下碰到的问题.
用的Django版本为1.4.
我比较喜欢用jquery的ajax来做表单提交(我觉得ajax比form方便...每个人喜好不同吧~)
ajax提交一下,结果出事了....403错误,CSRF,还好在MVC里面也有这货,对这名字不陌生了~但是MVC里面不报错.怎么Django就报错了..貌似Django更看重安全问题么~
说下解决方法,google了一大圈,说什么添加MIDDLEWARE_CLASSES...全是扯淡.
最终解决方法如下:
MIDDLEWARE_CLASSES根本不需要动,Django默认就行.
$(document).ready中加入以下js代码(PS:必须使用jquery,如果不想用,请自行转换成js代码):
1 jQuery(document).ajaxSend(function(event, xhr, settings) { 2 function getCookie(name) { 3 var cookieValue = null; 4 if (document.cookie && document.cookie != '') { 5 var cookies = document.cookie.split(';'); 6 for (var i = 0; i < cookies.length; i++) { 7 var cookie = jQuery.trim(cookies[i]); 8 // Does this cookie string begin with the name we want? 9 if (cookie.substring(0, name.length + 1) == (name + '=')) { 10 cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); 11 break; 12 } 13 } 14 } 15 return cookieValue; 16 } 17 function sameOrigin(url) { 18 // url could be relative or scheme relative or absolute 19 var host = document.location.host; // host + port 20 var protocol = document.location.protocol; 21 var sr_origin = '//' + host; 22 var origin = protocol + sr_origin; 23 // Allow absolute or scheme relative URLs to same origin 24 return (url == origin || url.slice(0, origin.length + 1) == origin + '/') || 25 (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') || 26 // or any other URL that isn't scheme relative or absolute i.e relative. 27 !(/^(\/\/|http:|https:).*/.test(url)); 28 } 29 function safeMethod(method) { 30 return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); 31 } 32 33 if (!safeMethod(settings.type) && sameOrigin(settings.url)) { 34 xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); 35 } 36 });
然后在templates任意位置加入{% csrf_token %}
接下来修改view
方法如下:
from django.core.context_processors import csrf from django.shortcuts import render_to_response, get_object_or_404 def index(request): c = {} c.update(csrf(request)) return render_to_response('index.html',c)
现在提交就木有问题啦~
希望在这里碰壁的朋友越来越少~