django csrf_token不打印隐藏的输入字段

pro*_*ngs 7 python django csrf django-csrf

我的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', )
Run Code Online (Sandbox Code Playgroud)

在我的模板中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>
Run Code Online (Sandbox Code Playgroud)

所以当我在浏览器中打开主页并查看源代码时,没有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= ......
Run Code Online (Sandbox Code Playgroud)

我错过了什么?

更新:这有帮助.

Mar*_*mro 8

您需要使用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))
Run Code Online (Sandbox Code Playgroud)

顺便说一句:csrf_protect不推荐使用装饰器,因为如果你忘了使用它,你就会有一个安全漏洞.