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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With