CSRF验证失败 - Django

时间:2015-03-29 16:23:28

标签: python django csrf

好的,所以我一直在浏览Rango,Django教程:

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

我实现的大致相同,但改变它以向Guardian Open-Platform API发出请求。我认为大部分都是正确的但每次我尝试搜索都会得到CSRF token missing or incorrect错误。我有一个很好的搜索并尝试了很多不同的解决方案,但似乎没有任何工作!

我在下面列出了搜索页面html,views和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()

如果还有其他任何有用的东西,请告诉我,我会添加它。

提前致谢!!

1 个答案:

答案 0 :(得分:3)

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