简体   繁体   中英

Saving file uploaded via ajax to Django model ImageField

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!

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM