Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django csrf_token not printing hidden input field

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.

like image 669
prongs Avatar asked Feb 12 '12 09:02

prongs


2 Answers

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.

like image 118
Mariusz Jamro Avatar answered Sep 20 '22 08:09

Mariusz Jamro


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)
like image 29
Burhan Khalid Avatar answered Sep 19 '22 08:09

Burhan Khalid