2012-02-12 84 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)) 

裝飾的使用,因爲如果您忘記使用它,你將有一個安全漏洞。使用這兩種方法的「腰帶和大括號」策略很好,並且會產生最小的開銷。