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

2024-04-15

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

这是我的表格:

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

视图.py:

Try 1:

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

Try 2:

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

Try 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'),
]

索引.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>

注册.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>

For the {% csrf_token %}标签要工作,您必须确保模板使用请求对象呈现(请参阅the docs https://docs.djangoproject.com/en/1.9/ref/csrf/#how-to-use-it).

最简单的方法是使用render https://docs.djangoproject.com/en/1.9/topics/http/shortcuts/#render快捷方式而不是render_to_response https://docs.djangoproject.com/en/1.9/topics/http/shortcuts/#render-to-response. The 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})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Django 1.9 CSRF 验证失败。请求已中止 的相关文章