4

The file is available as raw data in the request. How am I supposed to transform it to be saved on the disk represented by the ImageField inside a model.

Tried stuff:

file_ = File(request)
modelinstance.picture.save(filename, file_, save=False)
modelinstance.save()

and some variants of the above. An example on how to do this inside the django view would help.

Thanks!

Pratik Mandrekar
  • 9,362
  • 4
  • 45
  • 65

2 Answers2

1

If you used a ModelForm, you wouldn't have anything special to do. ModelForm handles FileField/ImageField automatically.

If you really want to do it manually, django has docs

jpic
  • 32,891
  • 5
  • 112
  • 113
  • That's only part of the question. The actual question is that my file is not in request.FILES since it is a ajax XHR request. So how do I read it from there and assign to my ImageField – Pratik Mandrekar Oct 22 '12 at 16:32
  • You mean you have the file base64-encoded or something similar, inside the XHR request? That's interesting. Check what the file-field wants. A file object? Does it need to be already saved on disk? – Lars Wikman Oct 22 '12 at 19:55
  • It is very complex to upload a file via ajax, this plugin makes it easy http://www.malsup.com/jquery/form/ Also you should improve your question, how is it that "your file is not in request.FILES" in a comment and not in the question ? humhum ... – jpic Oct 23 '12 at 08:36
1

Solved it like this

filename = request.GET[ 'yourfilename' ]

from django.core.files.uploadedfile import SimpleUploadedFile
file_contents = SimpleUploadedFile("%s" %(filename), request.raw_post_data)

modelinstance.picture.save(filename, file_contents, True)
Pratik Mandrekar
  • 9,362
  • 4
  • 45
  • 65