2

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

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 对我不起作用。我很困惑。

4

2 回答 2

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>
于 2013-05-06T16:01:52.647 回答
0

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

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

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

return render_to_response(template_name, locals())
于 2013-05-06T14:54:45.703 回答