简体   繁体   English

Django:未设置CSRF Coo​​kie

[英]Django: CSRF cookie not set

I want to post a form in my django project resulting in a "CSRF cookie not set." 我想在django项目中发布一个表单,导致“ CSRF cookie未设置”。 error. 错误。

views.py 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 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: 在生成的页面中,我可以看到csrf输入字段:

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

Any idea, how to fix that? 任何想法,如何解决?

I had this problem a while ago: Django - AJAX not working due to csrf token not working on windows 我前一阵子遇到了这个问题: Django-由于csrf令牌在Windows上不起作用,AJAX无法正常工作

In short, put @ensure_csrf_cookie before your view definition. 简而言之,将@ensure_csrf_cookie放在视图定义之前。

ie

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM