加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 12:40:07 所属栏目:Python 来源:网络整理
导读: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 pho
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%},但没有运气

谢谢

UPDATE
我在日志中看到了这些

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

解决方法

将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) )

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读