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

CSRF ミドルウェアを使用するには、RequestContext を使用する必要があります。

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

ところで:csrf_protectデコレータの使用はお勧めしません。使用を忘れると、セキュリティ ホールができてしまうからです。

于 2012-02-12T09:25:37.537 に答える
1

1.3 になったら (そうあるべきです)、renderショートカットはそれを行うためのよりコンパクトな方法を提供します:

from django.shortcuts import render

def some_view(request):
    return render(request, 'template.html', context_dict)
于 2012-02-12T09:50:52.380 に答える
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))

デコレータの使用は、それ自体を使用することをお勧めしません。使用するのを忘れると、セキュリティ ホールができてしまうからです。両方を使用する「ベルトとブレース」戦略は適切であり、最小限のオーバーヘッドしか発生しません。

于 2012-02-12T12:11:32.260 に答える