开发者

SWFUpload + Django 1.2 CSRF problem

Whenever I try to upload a file using SWFUpload on Django 1.2, I get an HTTP 403 error. I'm sure this is a CSRF error because when I use the @csrf_exempt decorator in works fine.

window.onload = function {
    var settings = {
        ...
        post_params: {
            "csrfmiddlewaretoken": "{{csrf_token}}"
        },
        ...
    };

var swfu = new SWFUpload(settings);
};

I also tried to use the SWFUpload.addPostParam() without success

var swfu = new SWFUpload(settings);
swfu.addPostParam('csrfmiddlewaretoken', '{{csrf_token}}'); 

I'm sure I'm passing the token to the开发者_如何转开发 template because I can see it in the source. The directory I'm uploading to is writable. I chmod 777 it.

Any ideas?


Apart from "csrfmiddlewaretoken" in post params, django also expects CSRF cookie to be set correctly, otherwise user will get a 404 error.

In your middleware to copy the session token into cookie, copy csrftoken as well and it will work. I followed instructions from http://blog.fogtunes.com/2009/11/howto-integrate-swfupload-with-django/ and updated the middleware part like the following and it works:

class SWFUploadMiddleware(object):

def process_request(self, request):
    if (request.method == 'POST') and (request.path == reverse('uploads.views.manual')) :  
        if 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']   
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜