Search code examples
djangocsrfswfupload

SWFUpload with Django 1.2 csrf problem


I`m trying to upload files to Django with SWFUpload. Found this article Django with SWFUpload. But found one problem. In Django 1.2 a csrf requires a csrf token to be send on every form submit, and it includes files that are send with SWFUpload.So uploading doesnt until i turn off csrf ( globally or for view using @csrf_exempt decorator). Is there a better way to handle this rather than turning off csrf?

I know that i can pass custom data with SWFUpload post_params: {"csrfmiddlewaretoken" : ""},. But i don`t know how to get only value of csrf token in template, not a full input tag.


Solution

  • To retrieve the csrf token itself, you'll need to resort to using some of Django's internals. First off, include this line at the top of your view.

    from django.middleware.csrf import get_token
    

    Now, when passing parameters to your template, do something like

    def my_view(request):
        return render_to_response("index.html", {"csrf_token": get_token(request)})
    

    In your template, just reference the token with {{ csrf_token }}.