How to upload files using ajax?

How to upload a image using ajax in django?

  • Background : I have a simple model form with a image field. class XYZForm(ModelForm):     class Meta:         model = XYZ         fields = ( 'file',) The model is class XYZ(models.Model):     url = models.URLField(null = True)     file = models.ImageField(upload_to=get_photo_storage_path, null = True) Problem: I am submitting this form via ajax. But this form is not validating, as the file is not being stored. Is there a particular way of submitting forms with files via ajax ? P.S. :- request.FILES is empty in the view, where the form is being submitted

  • Answer:

    This method works well: http://kuhlit.blogspot.com/2011/04/ajax-file-uploads-and-csrf-in-django-13.html Also - unless you have a specific reason to store images via the ImageField, try using a string field that contains the path to the image on your hard drive (make sure it's backed up). Storing large images (or any binary data) in rows in a DB is not efficient ...

Joseph Misiti at Quora Visit the source

Was this solution helpful to you?

Other answers

posted a link to a really clear example.  Good coverage of how to handle the CSRF protection.  However, you may not need to handle image paths manually -- read this for more info on setting up a callback to generate the path: http://scottbarnham.com/blog/2008/08/25/dynamic-upload-paths-in-django/

Don Marti

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.