1

I want to post a form in my django project resulting in a "CSRF cookie not set." error.

views.py

from django.shortcuts import render
from django.template import RequestContext
from pyBikeMilesApp.models import Eintrag
from django.template.context_processors import csrf

# Create your views here.
def index(request):
  if request.method == 'POST':
    print(request.POST)

  # Get all posts from DB
  eintraege = Eintrag.objects
  return render(request,'index.html',{'Eintraege': eintraege})

index.html

{% extends 'base.html' %}

{% block title %}BikeMiles{% endblock %}

{% block content %}
<div class="col-md-12">
  <table class="table table-striped">
    <tr>
      <th>gefahrene KM</th>
      <th>Datum</th>
      <th>Kommentar</th>
      <th>Aktion</th>
      {% for eintrag in Eintraege %}
      <tr>
        <td>{{ eintrag.kommentar }}</td>
        <form method="post" action="http://127.0.0.1:8000/">
           {% csrf_token %}
          <input type="hidden" name="id" value="{{eintrag.id}}">
          <input type="submit" class="btn btn-xs btn-danger" value="delete" >
        </form>
      </tr>
      {% endfor %}
    </table>
  </div>
  {% endblock %}

in the generated page i can see the csrf input field:

<input type='hidden' name='csrfmiddlewaretoken' value='zzRnENjz6wrUP8Op8IVOIDsUVvclY37k' />

Any idea, how to fix that?

Dakkar
  • 5,682
  • 5
  • 22
  • 28
  • 1
    What happen if you change `action="http://127.0.0.1:8000/"` to `action="/">`? – falsetru Aug 02 '15 at 09:18
  • possible duplicate of [Django CSRF check failing with an Ajax POST request](http://stackoverflow.com/questions/5100539/django-csrf-check-failing-with-an-ajax-post-request) – elssar Aug 02 '15 at 11:55
  • ah repacing the URL with the path fixed it. strange. Thank u very much – Dakkar Aug 02 '15 at 13:32

1 Answers1

3

I had this problem a while ago: Django - AJAX not working due to csrf token not working on windows

In short, put @ensure_csrf_cookie before your view definition.

i.e.

# Create your views here.
@ensure_csrf_cookie
def index(request):
Community
  • 1
  • 1
Neurion
  • 379
  • 6
  • 15