2012-02-12 40 views
7

views.pyDjango的csrf_token不打印隐藏的输入字段

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= ...... 

我错过了什么?

UPDATEthis帮助。

回答

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

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

+0

谢谢,这让我疯狂。很高兴这很简单。 – Cerin 2015-02-02 20:10:08

1

一旦你在1.3(你应该是),则render快捷酒店做的更紧凑的方式:

from django.shortcuts import render 

def some_view(request): 
    return render(request, 'template.html', context_dict) 
0

请参阅从Django的文档片段。

装饰器方法 与其将CsrfViewMiddleware添加为一揽子保护,您可以在需要保护的特定视图上使用具有完全相同功能的csrf_protect装饰器。 必须将它用于将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)) 

装饰的使用,因为如果您忘记使用它,你将有一个安全漏洞。使用这两种方法的“腰带和大括号”策略很好,并且会产生最小的开销。