Search code examples
pythondjangocsrfdjango-csrf

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.


Solution

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