Third, cross-site request forgery
First, Introduction
Django provides users with the ability to prevent cross-site request forgery, which is accomplished through middleware django.middleware.csrf.CsrfViewMiddleware. For Django, the ability to set up anti-cross-site request forgery is divided into global and local.
Global:
Middleware Django.middleware.csrf.CsrfViewMiddleware
Local:
- @csrf_protect, force the anti-cross-site request forgery feature for the current function, even if the global middleware is not set in Settings.
- @csrf_exempt, cancels the current function of anti-cross-site request forgery, even if the global middleware is set in Settings.
Note: from DJANGO.VIEWS.DECORATORS.CSRF import Csrf_exempt,csrf_protect
Second, the application
1. Normal forms
Set return value in Veiw: 2 return render_to_response (' account/login.html ', data,context_instance= or 4 return Render (Request, ' xxx.html ', data) 5 in HTML set token:7 {% Csrf_token%}
2. Ajax
For a traditional form, tokens can be sent back to the server via a form, and for Ajax, use the following method.
view.py
1 from django.template.context import requestcontext 2 # Create your views here. 3 4 5 def Test (Request) : 6 7 If Request.method = = ' POST ': 8 print request. POST 9 return HttpResponse (' OK ') return render_to_response (' app01/test.html ', context_ Instance=requestcontext (Request))
Text.html
1 <! DOCTYPE html> 2 } 9 <input type= "button" onclick= "Do ();" Value= "Do It"/>11 <script src= "/static/plugin/jquery/jquery-1.8.0.js" ></script>13 <script S Rc= "/static/plugin/jquery/jquery.cookie.js" ></script>14 <script type= "Text/javascript" >15 var c Srftoken = $.cookie (' Csrftoken ')); Csrfsafemethod Function (method) {//These HTTP methods do not require CSRF PR Otection19 return (/^ (get| head| options| TRACE) $/. }21 $.ajaxsetup ({ beforesend:function (XHR, Settings) {(!csrfsafemet Hod (settings.type) && !this.crossdomain) {xhr.setrequestheader ("X-csrftoken", Csrftoken); }27 }), and the function do () { $.ajax ({url: "/app01/test/", data:{id:1},33 type: ' P OST ', success:function (data) { console.log (data); }37 }); }40 </script> </body>42
MORE: https://docs.djangoproject.com/en/dev/ref/csrf/#ajax
Python path--web--2--django-6-cross-site request forgery