2014-04-03 50 views
0

儘管我正在使用{%csrf_token%},但我仍得到CSRF驗證失敗。錯誤在哪裏?儘管{%csrf_token%},CSRF驗證失敗

<html> 
<head> 
    <title>Name</title> 
</head> 
<body> 
    <h1>Tasks</h1> 
    <form action="" method="post"> 
     {{ form.as_p }} 
     <input type="submit" name="add" value="add"> 
     {% for a in comments %} 
     <h3>{{ a.body}}</h3> 
     <input type="submit" name="delete" value="delete" /> 
     <input type="hidden" name="idcomment" id="{{a.id}}" value="{{a.id}}"/> 
     {% csrf_token %} 
    </form> 
    {% endfor %} 
</body> 
</html> 
+0

你有'django.middleware.csrf.CsrfViewMiddleware'在'MIDDLEWARE_CLASSES'? – alecxe

+0

另外,您在視圖中使用了什麼方法進行渲染? 'render_to_response'或'render' –

+0

是的,我在MIDDLEWARE_CLASSES中有這個 –

回答

1

可能的解決方案:

<html> 
<head> 
    <title>Name</title> 
</head> 
<body> 
    <h1>Tasks</h1> 
    <form action="" method="post"> 
     {% csrf_token %} 
     {{ form.as_p }} 
     <input type="submit" name="add" value="add"> 
     {% for a in comments %} 
     <h3>{{ a.body}}</h3> 
     <input type="submit" name="delete" value="delete" /> 
     <input type="hidden" name="idcomment" id="{{a.id}}" value="{{a.id}}"/> 
     {% endfor %} 
    </form> 
</body> 
</html> 

另一種解決方案

from django.shortcuts import render 

#your view 
context = {} 
return render(request, 'your_file.html', contest) 
2

for循環使許多</form>標籤和csrf令牌,因爲它關閉form外而內開始。