CSRF verification failed despite {% csrf_token %}

2020-08-05 10:25发布

问题:

I get CSRF verification failed despite the fact that I am using {% csrf_token %}. Where is mistake?

<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>

回答1:

Possible solutions:

<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>

Another solution

from django.shortcuts import render

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


回答2:

Your for loop renders many </form> tags and csrf tokens as it closes outside the form while starting within.



标签: django