Django 1.9 CSRF 验证失败.请求中止 [英] Django 1.9 CSRF verification failed. Request aborted

查看:22
本文介绍了Django 1.9 CSRF 验证失败.请求中止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 CSRF 时遇到问题.我知道必须使用:{% csrf_token %} 但问题是一样的.

I have a problem with CSRF. I know must use: {% csrf_token %} but the problem is the same.

这是我的表格:

<form action="." method="post">
     {% csrf_token %}
    .......
</form>

views.py:

尝试 1:

def registro(request):
    return HttpResponse('Hola')

尝试 2:

def registro(request):
    c={}
    c.update(csrf(request))
    return render_to_response('registro.html',c)

尝试 3:

def registro(request):
    c={}
    return render(request,'nuevavista.html',c)

完整的views.py:

complete views.py:

from django.shortcuts import render_to_response, HttpResponse, render,RequestContext
from django.core.context_processors import csrf
from django.utils import timezone
from .models import Articulo
from django.template import RequestContext

# Create your views here.


#Nueva vista

def nuevavista(request):
    #return render_to_response(request,'nuevavista.html')
    #return render(request,'blog/nuevavista.html')
    #return HttpResponse('Nueva web')
    return render_to_response(request,'nuevavista.html')
    #return render_to_response('nuevavista.html',context_instance=RequestContext(request)) 

def registro(request):
    #if request.method=='POST':
    c={}
    #c.update(csrf(request))
    #return render_to_response('registro.html',c)
    #return    render(request,'registro.html',context_instance=RequestContext(request))
    #return HttpResponse('Hola')
    return render(request,'nuevavista.html',c)

def home(request):
    articulos = Articulo.objects.all().order_by('-fecha')
    return render_to_response('index.html',{'articulos':articulos})

urls.py:

from django.conf.urls import include,url
from django.contrib import admin
admin.autodiscover()

urlpatterns = [
    #url de nueva vista
    url(r'^nuevavista','blog.views.nuevavista',name="nuevavista"),
    url(r'^registro','blog.views.registro',name="registro"),


    url(r'^admin/', admin.site.urls),
    url(r'^blog/', 'blog.views.home',name='home'),
]

index.html:

index.html:

<!doctype html>
{% load staticfiles %}
<html lang="en">
<head>
  <meta charset="utf-8">

  <title>Mi pagina</title>

  <!--<link rel="stylesheet" href="css/styles.css?v=1.0">-->
 <link rel="stylesheet" href="{% static 'css/estilo.css' %}" />
</head>
<body>
    <p>Mi primera pagina </p>

    {% for articulo in articulos %}
    <h1> <a href="{% url 'blog.views.nuevavista' %}" >Titulo   {{articulo.titulo}}</a></h1>
    <p>Autor {{articulo.autor}}</p>
    <p>Texto del articulo {{articulo.texto}}</p>
    <p>Fecha {{articulo.fecha}} </p>
    {% endfor %}


    <p>Formulario</p>
    <form action="." method="post">
        {% csrf_token %}
        <!--<input type='hidden' name='csrfmiddlewaretoken' value='randomchars'/>-->
        <label> Nombre: </label>
        <input id="nombre" type="text" maxlength="100">
        <input type="submit" value="envíar">
    </form>


</body>
</html>

registro.html:

registro.html:

<!doctype html>
{% load staticfiles %}
<html lang="en">
<head>
  <meta charset="utf-8">

  <title>Mi pagina</title>

  <!--<link rel="stylesheet" href="css/styles.css?v=1.0">-->
 <link rel="stylesheet" href="{% static 'css/estilo.css' %}" />
</head>
<body>
    <p>Registro </p>    
</body>
</html>

推荐答案

要使 {% csrf_token %} 标签起作用,您必须确保模板与请求对象一起呈现(请参阅 文档).

For the {% csrf_token %} tag to work, you must ensure that the template is rendered with the request object (see the docs).

最简单的方法是使用 渲染 快捷方式而不是 render_to_response.不推荐使用 render_to_response 方法,并且将来可能会从 Django 中删除.

The easiest way to do this is to use the render shortcut instead of render_to_response. The render_to_response method is not recommended, and is likely to be removed from Django in future.

from django.shortcuts import render

def registro(request):
    c = {}  
    # put any other context you need in c
    # no need for c.update(csrf(request)) because we're using render    
    return render(request, 'registro.html', c)

您需要更新在其模板中使用 csrf_token 的所有视图.在这种情况下,您尚未更新在 index.html 模板中呈现表单的 home 视图.

You need to update any views that use csrf_token in their templates. In this case, you haven't updated the home view that renders the form in the index.html template.

def home(request):
    articulos = Articulo.objects.all().order_by('-fecha')
    return render(request, 'index.html', {'articulos':articulos})

这篇关于Django 1.9 CSRF 验证失败.请求中止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆