4

I am creating a web application using django and backbone.js. The problem is I need to upload files to the server. How do I link the backbone model with a file? Thus when I execute model.save() the file is uploaded to the server.

EDIT: just to make things clear. What I want to do is I want to link a input file box with the backbone model. So when the user selects a file from his/her computer I should be able to link that file with the backbone model. And when I call the model.save() in the backbone script it should send the file along with rest of the model.

2
  • Models in backbone.js use Ajax calls to send resource attributes to the server. These attributes are translated to params to send over the wire. I'm not sure if what you ask is a realistic expectation. Commented May 28, 2011 at 1:55
  • 2
    I think you have confused potential answerers of this question by mentioning django. The problem is entirely within backbone.js and the server side is irrelevant. I have exactly the same issue but my server side happens to be PHP. This guy has the same issue, but he's using Rails: stackoverflow.com/questions/6500379/file-upload-with-backbone Commented Sep 5, 2011 at 14:53

2 Answers 2

0

Basically the Web browser decides when a file is uploaded, not the server. The server may receive the file in request.FILES. You can then handle the model.save() after the browser has submitted the file. For more information you should see Django's very good documentation site: http://docs.djangoproject.com/en/dev/topics/http/file-uploads/?from=olddocs

The model in backbone.js provides a means to use a model to process the data. BUt Django has its own facilities for receiving files as noted above.

Sign up to request clarification or add additional context in comments.

1 Comment

I do know djnago provides a mechanism for uploading files and saving them, thank you for that. But my question is how do i link, lets say, a input file tag to the backbone model. Thus when I call model.save in backbone it would send the file to the server.
0

The problem is that you can't use file upload with AJAX directly. The common workaround is to submit a form to a hidden iframe.

You can use jQuery Form plugin. It provides ajaxSubmit method, it works like jQuery.ajax call but uses hidden iframe so it can upload files.

Also you need to override Backbone.sync or override sync on a per-model basis and replace $.ajax call with $(someForm).ajaxSubmit call

On server you should return JSON string with id parameter and file parameter containing file url

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.