怎么在django中實現csrf?針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
如果是ajax提交,可以按照下面的方式處理
<script src="/static/jq/jquery-3.3.1.js"></script> <script src="/static/jq/jquery.cookie.js"></script> <script> $(function () { ajax_buttion() }) function ajax_buttion() { $("#btn").bind("click",function () { $.ajax( { url:"/test/app1/", type:"post", data:{ username:"root", pwd:"admin" }, headers:{ "X-CSRFToken":$.cookie("csrftoken") }, sucess:function (data) { console.log(data) } } ) }) } </script>
可以設置一個全局的設置,然后在$(function){
}中執行函數
$(function () { ajax_buttion() $.ajaxSetup() })
如果是form表單提交,則可以按照下面的方式處理
<form action="/test/app1/" method="post"> {% csrf_token %} <input type="text" name="uname"> <input type="submit" value="submit"> <input type="button" value="ajax" id="btn"> </form>
然后返回使用render的方式返回
def test(request): # int("hahah") # print(settings.C) print("test------->views",time.time()) print(request.method) print("_".center(100,"-")) print(request) # return HttpResponse("last_app1") return render(request,"test.html")
中間件里csrf默認是全局都生效的,但是如果我們有需求,比如全局生效,但是我某個函數不需要使用csrf該怎么辦;或者我的全局不設置csrf,但是對某個視圖函數需要采用csrf,該怎么辦
這里就需要導入2個模塊
from django.views.decorators.csrf import csrf_exempt from django.views.decorators.csrf import csrf_protect
然后在視圖函數中使用使用裝飾器來裝飾視圖函數
下面的例子就是起到全局啟動csrf,但是我這個函數不啟動csrf
@csrf_exempt def test(request): # int("hahah") # print(settings.C) print("test------->views",time.time()) print(request.method) print("_".center(100,"-")) print(request) # return HttpResponse("last_app1") return render(request,"test.html")
下面的例子就是全局不啟用csrf,但是我這個函數不啟動csrf
@csrf_protect def test(request): # int("hahah") # print(settings.C) print("test------->views",time.time()) print(request.method) print("_".center(100,"-")) print(request) # return HttpResponse("last_app1") return render(request,"test.html")
關于怎么在django中實現csrf問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業資訊頻道了解更多相關知識。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。