CSRF令牌丢失或不正确(我知道,之前已被问过!)

时间:2012-02-09 03:10:29

标签: python django csrf

通过Google,stackoverflow和docs.djangoproject.com两天来寻找CSRF问题的解决方案。

免责声明,我是Django的初学者,并继续阅读 django的权威指南 - 网络开发正确完成。好吧,显然我遇到了错误:-(

请参阅下面的一个这样的尝试,看看你是否可以指出任何错误,因为我已经尝试了stackoverflow上的所有建议,但还没有运气:

view.py:

from django.shortcuts import render_to_response
from django.template import RequestContext

def add_vehicle(request):
    return render_to_response('vehicle.html', RequestContext(request, {}))

vehicle.html:

{% extends "base.html" %}
{% block title %}Vehicle Registration{% endblock %}
{% block content %}
<html>
<head>
</head>
<body>

<form action="/vehicle/" method="post"> {% csrf_token %}
    <table width=100%>
        <tr>
            <td>Reg #:</td>
            <td><input type="text" name="regnumber"></td>
            <td></td>
        </tr>
        <tr>
            <td>Model:</td>
            <td><input type="text" name="model"></td>
            <td></td>
        </tr>
        <tr>
            <td>Manufacturer:</td>
            <td><input type="text" name="manufacturer"></td>
            <td></td>
        </tr>
        <tr>
            <td>Year:</td>
            <td><input type="text" name="year"></td>
            <td></td>       
        </tr>
        <tr>
            <td>Chassis #:</td>
            <td><input type="text" name="chasisnumber"></td>
            <td></td>       
        </tr>
        <tr>
            <td></td>
            <td><input type="submit" value="Submit">
            <input type="submit" value="Clear">
            </td>
            <td></td>       
        </tr>
    </table>
</form>
</body>
</html>
{% endblock %}

我希望stackoverflow的代码不是太多。

现在,我一直在 CSRF令牌丢失或不正确

请协助。

编辑(添加错误详情)

settings.py看起来像这样:

MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)

以下是我打开vehicle.html页面时控制台显示的内容:

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.")

2 个答案:

答案 0 :(得分:4)

render_to_response的签名是render_to_response(template_name[, dictionary][, context_instance][, mimetype])所以你应该像下面这样调用它来确保将csrf令牌放入上下文中吗?

return render_to_response('vehicle.html', {}, context_instance= RequestContext(request))`

答案 1 :(得分:0)

您应该查看此文档 https://docs.djangoproject.com/en/dev/ref/contrib/csrf/

你可能错过了中间件