zoukankan      html  css  js  c++  java
  • django-csrf使用和禁用

    form表单使用csrf

    a. 基本应用
    	form表单中添加
    	{% csrf_token %}
    
    b. 全站禁用
    	# 'django.middleware.csrf.CsrfViewMiddleware',
    
    c. 局部禁用
    	'django.middleware.csrf.CsrfViewMiddleware',
    	
    	from django.views.decorators.csrf import csrf_exempt
    
    	@csrf_exempt
    	def csrf1(request):
    
    		if request.method == 'GET':
    			return render(request,'csrf1.html')
    		else:
    			return HttpResponse('ok')
    d. 局部使用
    	# 'django.middleware.csrf.CsrfViewMiddleware',
    	
    	from django.views.decorators.csrf import csrf_exempt,csrf_protect
    
    	@csrf_protect
    	def csrf1(request):
    
    		if request.method == 'GET':
    			return render(request,'csrf1.html')
    		else:
    			return HttpResponse('ok')
    

    ajax提交数据

    Ajax提交数据时候,携带CSRF:
    a. 放置在data中携带
    
    <form method="POST" action="/csrf1.html">
    	{% csrf_token %}
    	<input id="user" type="text" name="user" />
    	<input type="submit" value="提交"/>
    	<a onclick="submitForm();">Ajax提交</a>
    </form>
    <script src="/static/jquery-1.12.4.js"></script>
    <script>
    	function submitForm(){
    		var csrf = $('input[name="csrfmiddlewaretoken"]').val();
    		var user = $('#user').val();
    		$.ajax({
    			url: '/csrf1.html',
    			type: 'POST',
    			data: { "user":user,'csrfmiddlewaretoken': csrf},
    			success:function(arg){
    				console.log(arg);
    			}
    		})
    	}
    
    </script>
    				
    b. 放在请求头中
    			
    <form method="POST" action="/csrf1.html">
    	{% csrf_token %}
    	<input id="user" type="text" name="user" />
    	<input type="submit" value="提交"/>
    	<a onclick="submitForm();">Ajax提交</a>
    </form>
    <script src="/static/jquery-1.12.4.js"></script>
    <script src="/static/jquery.cookie.js"></script>
    
    <script>
    	function submitForm(){
    		var token = $.cookie('csrftoken');
    		var user = $('#user').val();
    		$.ajax({
    			url: '/csrf1.html',
    			type: 'POST',
    			headers:{'X-CSRFToken': token},
    			data: { "user":user},
    			success:function(arg){
    				console.log(arg);
    			}
    		})
    	}
    </script>
    
  • 相关阅读:
    BZOJ2330 SCOI2011糖果
    BZOJ 3812主旋律
    模板更新 扩展卢卡斯
    BZOJ4556 HEOI2016字符串
    CodeForces700E Cool Slogans
    Atcoder Contest069F:Flag
    计算几何模板(更新中......)
    BZOJ4003 JLOI2015城池攻占
    BZOJ3772精神污染
    HDU5919 SequenceⅡ
  • 原文地址:https://www.cnblogs.com/zouruncheng/p/7161534.html
Copyright © 2011-2022 走看看