Django默认是开启CSRF的
<form action="/login/" method="POST">
{% csrf_token %}
<input type="text" name="user"/>
<input type="password" name="pwd"/>
<input type="checkbox" name="rmb" value="1"/>
<input type="submit" value="登录"/>
</form>
<script src="/static/jquery-1.12.4.js"></script>
<script src="/static/jquery.cookie.js"></script>
<script>
$(function(){
$.ajaxSetup({
beforeSend:function(xhr,settings){
xhr.setRequestHeader('X-CSRFtoken',$.cookie('csrftoken'))
}
});
$('#btn1').click(function () {
$.ajax({
url: '/login/',
type: 'POST',
data: {'user': 'root', 'pwd': '123'},
success:function(arg){
}
})
});
$('#btn2').click(function () {
$.ajax({
url: '/login/',
type: 'POST',
data: {'user': 'root', 'pwd': '123'},
success:function(arg){
}
})
})
})
</script>
已配置情况下,取消csrf机制
from django.views.decorators.csrf import csrf_exempt, csrf_protect
@csrf_exempt
def index(request):
if request.session.get('is_login', None):
return render(request, 'index.html', {'username': request.session['username']})
else:
return HttpResponse('错误')
未配置情况下,添加csrf机制
from django.views.decorators.csrf import csrf_exempt, csrf_protect
@csrf_protect
def index(request):
if request.session.get('is_login', None):
return render(request, 'index.html', {'username': request.session['username']})
else:
return HttpResponse('错误')