Django:没有设置CSRF cookie

时间:2015-08-02 09:14:58

标签: python django django-csrf

我想在我的django项目中发布一个表单,导致未设置" CSRF cookie。"错误。

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

在生成的页面中,我可以看到csrf输入字段:

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

任何想法,如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

我前一段时间遇到过这个问题:Django - AJAX not working due to csrf token not working on windows

简而言之,将@ensure_csrf_cookie放在视图定义之前。

即。

# Create your views here.
@ensure_csrf_cookie
def index(request):