【问题标题】:CSRF Verification Failed - DjangoCSRF 验证失败 - Django
【发布时间】:2015-06-02 14:36:22
【问题描述】:

好的,所以我一直在学习 Rango,Django 教程:

(http://www.tangowithdjango.com/book17/chapters/bing_search.html)

我实现的基本相同,但对其进行了更改以向 Guardian Open-Platform API 发出请求。我认为其中大部分是正确的,但每次我尝试搜索时都会收到CSRF token missing or incorrect 错误。我进行了很好的搜索并尝试了很多不同的解决方案,但似乎没有任何效果!

我在下面包含了 searchpage html、views 和 Guardian_search 模型。

搜索.html:

{% extends 'rango/base.html' %}
{% load staticfiles %}

{% block title %}Search{% endblock %}

{% block body_block %}

<div class="page-header">
    <h1>Search with Rango"</h1>
</div>

<div class="row">
    <div class="panel panel_primary">
        </br>
        <form class="form-inline" id="user_form" method="post" action="{ url 'search' %}">
        {% csrf_token %}
            <!-- Display the search form elements here -->
            <input class="form-control" type="text" size="50" name="query" value="" id="query" />
            <input class="btn btn-primary" type="submit" name="submit" value="Search" />
            <br />
        </form>

        <div class="panel">
            {% if result_list %}
                <div class="panel_heading">   
                <h3 class="panel-title">Results</h3>
                <!-- Display search results in an ordered list -->
                <div class="panel-body">
                    <div class="list-group">
                        {% for result in result_list %}
                            <div class="list-group-item">
                                <h4 class="list-group-item-heading"><a href="{{ result.url }}">{{ result.title }}</a></h4>
                                <p class="list-group-item-text">A summary here?</p>
                            </div>
                        {% endfor %}
                    </div>
                </div>
            {% endif %}
            </div>
        </div>
    </div>
</div>

{% endblock %}

views.py:

from django.template import RequestContext
from django.shortcuts import render_to_response
from rango.bing_search import get_content

def search(request):
    result_list = []
    if request.method == 'POST':
        query = request.POST['query'].strip()
        if query:
            result_list = get_content(query)
    return render_to_response('rango/search.html', {'result_list':result_list})

guardian_search.py​​:

import requests
import pprint as pp

def get_content():

    api_url = 'http://content.guardianapis.com/search?'
    payload = {
        'q':                    raw_input(''),
        'api-key':              'api_key',
        'page-size':            10,
        'show-editors-picks':   'true',
        'show-elements':        'None', #'audio', 'image', 'video', 'all'
        'show-fields':          'None', #'headline' , 'body'
        'field':                'None',
    }

    response = requests.get(api_url, params=payload)

    data = response.json()
    urlList = []

    for item in data['response']['results']:
        urlList.append({
        'url': item['webUrl'],
        'title': item['webTitle']})

    pp.pprint(urlList)
    return urlList

if __name__ == '__main__':
    get_content()

如果还有什么有用的,请告诉我,我会添加。

提前致谢!!

【问题讨论】:

    标签: python django csrf


    【解决方案1】:

    如果您使用render_to_response,则必须提供RequestContext 才能使 CSRF 令牌工作。

    return render_to_response('rango/search.html',
                              {'result_list':result_list},
                              context_instance=RequestContext(request))
    

    但是,您的教程的 Django 1.7 版本使用的更简单的解决方案是使用 render 快捷方式而不是 render_to_response

    from django.shortcuts import render
    
    render(request, 'rango/search.html', {'result_list':result_list})
    

    顺便说一句,您在action="{ url 'search' %}"&gt; 中缺少%

    【讨论】:

    • 太棒了。这与将guardian_search 函数q 作为raw_input 搜索词一起传递。谢谢!!
    猜你喜欢
    • 2012-09-08
    • 1970-01-01
    • 2017-03-29
    • 2011-06-14
    • 2020-03-24
    • 2014-05-23
    相关资源
    最近更新 更多