django csrf令牌错误(RequestContext不起作用)

时间:2013-05-06 14:46:28

标签: django django-csrf

我正在使用django 1.5.1,我必须在每个POST上使用{%csrf_token%}才能正常工作。请求对我不起作用,这里是我的设置,查看代码和模板代码。

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',
)

def show_rates(request, doc_id, template_name='rate.html'):
    doc = get_object_or_404(Doctor, id=doc_id)
    hos = doc.hospital
    docts = hos.doctor_set.all()
    page_title = doc.name
    hos_name = hos.name
    if request.method == "POST":
        postdata = request.POST.copy()
        form = AddToRateForm(postdata)
    else:
        form = AddToRateForm()
    return render(request, template_name, locals())

<form method="POST" action=".">
    {{ form.as_table }}
    <div class="row-fluid">
        <div class="span10">
        </div>
        <div class="span2">
            <button class="btn btn-block btn-primary" type="submit">Rate</button>
        </div>
    </div>
</form>

RequestContext对我不起作用。我很困惑。

2 个答案:

答案 0 :(得分:2)

MIDDLEWARE_CLASSES看起来不错。

这是您应该用于csrf的基本代码。

from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt, csrf_protect

@csrf_protect
#@csrf_exempt says to make an exemption on csrf, but of course is not secure.
#@csrf_exempt
def show_rates(request, doc_id, template_name='rate.html'):
    ...
    #I suppose  that locals() returns a dict()
    return render(request, template_name, locals())


<form method="POST" action="">
    {# Don't forget the following line #}
    {% csrf_token %}
    {{ form.as_table }}
    <div class="row-fluid">
        <div class="span10">
        </div>
        <div class="span2">
            <button class="btn btn-block btn-primary" type="submit">Rate</button>
        </div>
    </div>
</form>

答案 1 :(得分:0)

尝试更改视图定义以添加此装饰器:

@csrf_protect
def show_rates(request, doc_id, template_name='rate.html'):

并将您的返回响应更新为不包含context_instance。真的没必要。

return render_to_response(template_name, locals())