尽管{%csrf_token%},CSRF验证失败

时间:2014-04-03 18:57:57

标签: django

尽管我使用的是{%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>

2 个答案:

答案 0 :(得分:2)

您的for循环会在</form>开始时在csrf之外关闭时呈现许多form个代码和{{1}}代币。

答案 1 :(得分: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)