Django:即使添加了{%csrf_token%},CSRF验证也失败了

时间:2011-12-06 23:45:43

标签: python django

views.py:

def index(request):
    return render_to_response('index.html', {})

def photos(request, artist):
    if not artist:
        return render_to_response('photos.html', {'error' : 'no artist supplied'})
    photos = get_photos_for_artist(artist)
    if not photos:
        logging.error('Issue while getting photos for artist')
        return render_to_response('photos.html', {'error': 'no matching artist found'})
    return render_to_response('photos.html', {'photos': photos})  

Index.html:

<html>
    <head>
        <title>find artist photos </title>
    </head>
    <body>
        {% block error %} {% endblock %}
        <form action="/photos" method="POST">
            {% csrf_token %}
            <label for="artist">Artist : </label>
            <input type="text" name="artist">
            <input type="submit" value="Search">
        </form>
        {% block content %}{% endblock %}
    </body>
</html>

photos.html:

{% extends 'index.html' %}
{% block error %}
    {% if error %}
        <p> {{ error}} </p>
    {% endif %}
{% endblock %}

{% block content %}
    {% if photos %}
        {% for photo in photos %}
            {{ photo }}
        {% endfor %}
    {% endif %}
{% endblock%}

url.py:

urlpatterns = patterns('',
    (r'', index),
    (r'^time/$', current_datetime),
    (r'^photos/(\w+)$', photos)
)

我甚至尝试添加{% csrf_token %},但没有运气

谢谢

更新
我在日志中看到了这些

UserWarning: A {% csrf_token %} was used in a template, but the context did not provide the value.  This is usually caused by not using RequestContext.
  warnings.warn("A {% csrf_token %} was used in a template, but the context did not provide the value.  This is usually caused by not using RequestContext.")  

context_instance = RequestContext(request) **添加到render_to_response()**

之后

7 个答案:

答案 0 :(得分:9)

context_instance=RequestContext(request)添加到您将在其中使用表单的每个视图中:

return render_to_response('index.html', {}, context_instance=RequestContext(request) )


return render_to_response('photos.html', {'photos': photos}, context_instance=RequestContext(request) )

答案 1 :(得分:5)

假设您使用的是相当新版本的Django(1.3 / 1.4 / dev),您应该按照以下步骤操作:

  • settings.py中,将中间件django.middleware.csrf.CsrfViewMiddleware添加到。{1}} MIDDLEWARE_CLASSES列表。
  • 在模板中,使用表单中的{% crsf_token %}
  • 在您的视图中,确保通过以下方式使用django.core.context_processors.csrf上下文处理器:
    • 使用RequestContext
    • 中的django.template
    • 直接从from django.core.context_processors
    • 导入csrf处理器

实施例

from django.template import RequestContext
from django.shortcuts import render_to_response

def my_view(request):
    return render_to_response('my_template.html', {}, context_instance=RequestContext(request))

from django.core.context_processors import csrf
from django.shortcuts import render_to_response

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

参考

(后代和未来观众的详尽帖子)

答案 2 :(得分:3)

要解决的一些问题:

  • 请在网络浏览器中加载“索引”页面,执行“查看来源”,然后检查{% csrf_token %}是否正在展开。它应该替换为<input>标记。如果没有发生这种情况,那么您的索引页面就会出现问题。如果正确更换,则说明您的照片页面有问题。

  • index.html中的POST网址与urls.py中的任何模式都不匹配。您的urls.py似乎希望搜索字词成为网址的一部分,但事实并非如此 - 您将其作为HTTP POST参数发送。您需要通过request.POST

  • 访问它

答案 3 :(得分:2)

检查设置,如果您有此中间件:

'django.middleware.csrf.CsrfViewMiddleware'

https://docs.djangoproject.com/en/dev/ref/contrib/csrf/

答案 4 :(得分:1)

当您使用render_to_response以获取该模板标记的CSRF值时,您可能需要显式传入RequestContext实例。

http://lincolnloop.com/blog/2008/may/10/getting-requestcontext-your-templates/

答案 5 :(得分:0)

尝试使用@csrf_protect装饰器:

from django.views.decorators.csrf import csrf_protect
from django.shortcuts import render_to_response

@csrf_protect
def photos(request,artist):
    if not artist:
        return render_to_response('photos.html', {'error' : 'no artist supplied'})
    photos = get_photos_for_artist(artist)
    if not photos:
        logging.error('Issue while getting photos for artist')
        return render_to_response('photos.html', {'error': 'no matching artist found'})
    return render_to_response('photos.html', {'photos': photos})  

答案 6 :(得分:-1)

这对我有用:

{%csrf_token%} 在模板中,每个POST表单中都有一个{%csrf_token%}模板标记,用于定位内部网址。

在views.py中:

来自django.template的

导入RequestContext

...

...

...

返回render_to_response(“home.html”,{}, context_instance = RequestContext(request)