I'm trying to use a script for multiple file uploads, like swfupload or uploadify on my django application but no matter what I try, I always get a 403 forbidden error for the upload URL. If I try to run the 'same' code (just different links to same files) independently, it works like a charm.
Any idea if I'm missing something on my main code or is there some kind of setting that I don't know about?
This is totally related with CSRF protection
. In my case I solved that issue such that,
views.py
def photo_upload(request):
if request.method == 'POST':
for field_name in request.FILES:
....
....
return HttpResponse("ok", mimetype="text/plain")
else:
return render_response(request, 'wpphotos/post/photo_upload.html', {"csrf_token": get_token(request)},context_instance=RequestContext(request))
Because flash useses its own session while uploading, you should set csrf_token
value in your middleware such that
swfupload.py
from django.conf import settings
from django.core.urlresolvers import reverse
class SWFUploadMiddleware(object):
def process_request(self, request):
if (request.method == 'POST') and (request.path == reverse('project_name.module_name.views.photo_upload')) and \
request.POST.has_key(settings.SESSION_COOKIE_NAME):
request.COOKIES[settings.SESSION_COOKIE_NAME] = request.POST[settings.SESSION_COOKIE_NAME]
if request.POST.has_key('csrftoken'):
request.COOKIES['csrftoken'] = request.POST['csrftoken']
For the last step, you should set csrftoken
as post parameter in your javascript for SWFUpload
settings such that
photo_upload.html
window.onload = function() {
swfupload = new SWFUpload({
post_params: {
"csrfmiddlewaretoken": "{{csrf_token}}"
},
upload_url: "/module_name/post/photo_upload/",
flash_url: "/media/flash/swfupload.swf",
file_size_limit : "2.5 MB",
....
....
....
});
};