当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《Django:即使添加了{%csrf_token%},CSRF验证也失败了》经验,为你挑选了2个好方法。

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


    
        find artist photos 
    
    
        {% block error %} {% endblock %}
        
{% csrf_token %}
{% block content %}{% endblock %}

photos.html:

{% extends 'index.html' %}
{% block error %}
    {% if error %}
        

{{ error}}

{% 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()**之后



1> 小智..:

添加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) )


...或者如果您使用Django 1.3,您可以使用更短的版本:`render(request,'index.html',{})`https://docs.djangoproject.com/en/1.3/topics/ HTTP /快捷键/#渲染

2> sberder..:

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

settings.py,将中间件添加django.middleware.csrf.CsrfViewMiddlewareMIDDLEWARE_CLASSES列表中.

在模板中,使用{% crsf_token %}表单中的内容.

在您的视图中,确保django.core.context_processors.csrf通过以下方式使用上下文处理器:

使用RequestContext来自django.template

直接从中导入csrf处理器 from django.core.context_processors

例子

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)

参考

Django 1.3中的csrf或Django 1.4中的csrf

Django 1.3中的 RequestContext或Django 1.4中的RequestContext

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

推荐阅读
雨天是最美
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有