CSRF 验证失败 - Django

CSRF Verification Failed - Django

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

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

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

我在下面包含了搜索页面 html、视图和 guardian_search 模型。

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

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

提前致谢!!

如果您使用 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' %}"> 中缺少 %