7

my 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', )

in my template 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>

so when I open the homepage in browser and see the source code and there's no csrf token!

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

What did I miss?

UPDATE: this helped.

Community
  • 1
  • 1
prongs
  • 9,422
  • 21
  • 67
  • 105

3 Answers3

9

You need to use RequestContext in order to use CSRF middleware:

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: Use of csrf_protect decorator is not recommended, since if you forget to use it, you will have a security hole.

Mariusz Jamro
  • 30,615
  • 24
  • 120
  • 162
1

Once you are on 1.3 (which you should be), the render shortcut offers a more compact way of doing it:

from django.shortcuts import render

def some_view(request):
    return render(request, 'template.html', context_dict)
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
0

Please see the snippet from django document.

The decorator method Rather than adding CsrfViewMiddleware as a blanket protection, you can use the csrf_protect decorator, which has exactly the same functionality, on particular views that need the protection. It must be used both on views that insert the CSRF token in the output, and on those that accept the POST form data. (These are often the same view function, but not always). It is used like this:

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

Use of the decorator is not recommended by itself, since if you forget to use it, you will have a security hole. The 'belt and braces' strategy of using both is fine, and will incur minimal overhead.

Tairan
  • 1,099
  • 2
  • 6
  • 6