Irmantas Želionis
Irmantas Želionis

Reputation: 2324

CSRF verification failed despite {% csrf_token %}

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>

Upvotes: 0

Views: 155

Answers (2)

timo.rieber
timo.rieber

Reputation: 3867

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

Upvotes: 2

Anish Shah
Anish Shah

Reputation: 8169

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)

Upvotes: 1

Related Questions