Django csrf_token does not print 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 index.html template:

 <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 the browser and see the source code, and there is no csrf token there!

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

+7
source share
3 answers

You need to use RequestContext to use the 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)) 

By the way: using the csrf_protect decorator is not recommended, because if you forget to use it, you will have a security hole.

+8
source

Once you get up to 1.3 (what it should be), render offers a more compact way to do this:

 from django.shortcuts import render def some_view(request): return render(request, 'template.html', context_dict) 
+1
source

See the django document snippet.

Decorator Method Instead of adding CsrfViewMiddleware as a protective wrapper, you can use the csrf_protect decorator, which has exactly the same functionality for certain views that need protection. It should be used for both representations that insert the CSRF token into the output file, and those that accept POST form data. (This is often the same viewing function, but not always). It is used as follows:

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

Using the decorator alone is not recommended , because if you forget to use it, you will have a security hole. A strategy for using belts and braces to use both is good and will have minimal overhead.

0
source

All Articles