Django 1.9 CSRF验证失败。请求中止

时间:2016-02-18 00:07:47

标签: django django-forms

我对CSRF有疑问。我知道必须使用:{%csrf_token%}但问题是一样的。

这是我的表格:

<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:

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:

<!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:

<!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>

1 个答案:

答案 0 :(得分:2)

要使{% csrf_token %}代码生效,您必须确保使用请求对象呈现模板(请参阅the docs)。

最简单的方法是使用render快捷方式而不是render_to_response。不建议使用render_to_response方法,将来可能会从Django中删除。

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的所有视图。在这种情况下,您尚未更新在home模板中呈现表单的index.html视图。

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