7

我的views.py

from django.core.context_processors import csrf
from django.views.decorators.csrf import csrf_protect
from django.http import *
from django.template import *
from django.shortcuts import *
# Create your views here.
@csrf_protect
def homepage(request):
        return render_to_response('index.html', {'files':os.listdir('/home/username/public_html/posters') })
@csrf_protect
def upload(request):
        return render_to_response('list.html', )

在我的模板中index.html

<html>
<body>
<h1> All uploaded posters: </h1>
<form action='/posters/upload' method= 'POST'>{%csrf_token%}
<input type='file' name= 'uploadfile'>Upload new poster <input type="submit" value = "Upload">
</form>
{%for file in files %}
<a href = 'http://servername/~username/posters/{{file}}'>{{file}}</a> <br />
{%endfor%}
</body>
</html>

所以当我在浏览器中打开主页并查看源代码时,并没有 csrf 令牌!

<html>
<body>
<h1> All uploaded posters: </h1>
<form action='/posters/upload' method= 'POST'>
<input type='file' name= 'uploadfile'>Upload new poster <input type="submit" value = "Upload">
</form>

<a href= ......

我错过了什么?

更新有帮助。

4

3 回答 3

9

您需要使用 RequestContext 才能使用 CSRF 中间件:

from django.template import RequestContext

# In your view:
return render_to_response('index.html'
    {'files':os.listdir('/home/username/public_html/posters') },
    context_instance=RequestContext(request))

BTW:csrf_protect不建议使用装饰器,因为如果您忘记使用它,您将有一个安全漏洞。

于 2012-02-12T09:25:37.537 回答
1

一旦你使用 1.3(你应该是),渲染快捷方式提供了一种更紧凑的方式:

from django.shortcuts import render

def some_view(request):
    return render(request, 'template.html', context_dict)
于 2012-02-12T09:50:52.380 回答
0

请参阅 django 文档的片段。

装饰器方法 您可以在需要保护的特定视图上使用具有完全相同功能的 csrf_protect 装饰器,而不是添加 CsrfViewMiddleware 作为全面保护。它必须用于在输出中插入 CSRF 令牌的视图以及接受 POST 表单数据的视图。(这些通常是相同的视图函数,但并非总是如此)。它是这样使用的:

from django.views.decorators.csrf import csrf_protect
from django.template import RequestContext

@csrf_protect
def my_view(request):
    c = {}
    # ...
    return render_to_response("a_template.html", c,
                               context_instance=RequestContext(request))

不建议单独使用装饰器,因为如果您忘记使用它,您将有一个安全漏洞。使用两者的“腰带和大括号”策略很好,并且会产生最小的开销。

于 2012-02-12T12:11:32.260 回答