我收到錯誤CSRF驗證失敗。請求中止。CSRF驗證失敗。請求中止。在django ajax後
我有兩個文件一個是post.html和post_reply.html
我收到post_reply文件HTML中使用AJAX
到post.html的觀點是
def Display_post(request):
if request.method=="GET":
post = Post.objects.all()
#print post
data = []
for pos in post:
rep = Comment.objects.filter(post=post)
html = render_to_string('home/post_reply.html',{"post":post, "rep":rep})
return HttpResponse(html, mimetype="application/json")
所以現在我的回覆表單是post_reply文件,該文件正在進入post.html 現在我在這裏獲取CSRF驗證失敗。錯誤我用@csrf_exempt還是它不工作
Post.html
function save_reply(s)
{
//alert("hello");
//alert(s);
$.djangocsrf("enable");
var reply = $(".rep1").val();
var form = $("#"+s).parent();
//alert(reply);
csr = $("#"+s).prev().val();
alert(csr);
data = {
reply: reply,
};
$.ajax({
url: "/home/reply_save/"+s,
type: "POST",
data: form.serialize(),
success: function (response) {
alert("hello");
},
error: function() {
}
});
}
post_reply.html
{% for postone in post %}
<div class="testmain span11">
<div class="span1 test1"><img src="/media/{{postone.image}}" width="70" height="70" class="img-circle img-responsive"/></div>
<div class="span8 second">
<div class="test1 span5"><a><strong>{{postone.user}}</strong></a></div>
<br/>{{postone.time}}<br/><br/>
<div class="test1 span7">{{postone.post}}</div>
<div class="test span8"><img src="/media/{{postone.image}}" width="300" height="300"/></div>
<div class="span8" style="margin-bottom:2%;"><a class="replytopost" style="margin-left:-4%;" onclick='tog({{postone.pk}})'>Reply<span class="badge">{{postone.number_of_reply}}</span></a><input class="id5" type="hidden" value='{{postone.pk }}'></div>
<div id='{{postone.pk}}' class="hid">
<form method="post" action="." enctype="multipart/form-data" class="horizontal-form" role="form" id='{{postone.pk}}' style=""> {% csrf_token %}
<input type="text" name="lname" class="rep1" style="border-radius: 0px; "><input type="submit" onclick="save_reply({{postone.pk}})" class="btn btn-info replysave" id='{{postone.pk}}' value="Reply" style="border-radius: 0px; margin-bottom: 10px;"/>
</form>
<br/>{% for rep1 in rep %}
<div class="span1 test1"><img src="/media/{{postone.image}}" class="img-circle img-responsive" width="50" height="50"></div>
<div class="span6 third">
<div class="test1 span5"><a><strong>{{postone.user}}</strong></a></div>
<br/>
<div class="test1 span7">{{postone.post}}</div><br/>
<div class="test1 span6" style="margin-top:3%; margin-left:10%; font-size:0.9em;">{% load humanize %} {{postone.time|naturaltime}}</div>
</div>
{% endfor %}
</div>
</div>
</div>
{% endfor %}
最好不要這樣做。 csrf不僅僅是爲了讓你感到痛苦,它還保護項目免受[跨站點請求僞造](http://www.squarefree.com/securitytips/web-developers.html#CSRF) – stalk 2014-09-23 11:12:59
禁用csrf保護ajax調用會打開您的服務以進行各種攻擊:https://en.wikipedia.org/wiki/Cross-site_request_forgery。 – DimmuR 2016-03-12 18:32:21