How to save an image using django imageField?
Asked Answered
C

2

7

posting from an app (iOS android etc..) not a web form.

class someImage(models.Model):
    image = models.ImageField(upload_to= settings.SHARE_IMAGE_UPLOAD_PATH)

@csrf_exempt
def saveImage(request):

How to write the view? it receives an image in a post request. Every thing i find is form related (server newbie)

Christinachristine answered 11/1, 2012 at 16:20 Comment(2)
take a look at django-photologue, all what you want to do is already done :)Menefee
thanks, i don't need all these features, i'm looking for the most basic usage of imageField :)Christinachristine
S
16

Just because you're not using an actual HTML form to submit the data doesn't mean you can't use a ModelForm to process the request:

from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseNotAllowed
from django.utils import simplejson

def upload_view(request):
    if request.method == 'POST':
        form = UploadForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            result = {'success': True}
            return HttpResponse(simplejson.dumps(result), mimetype='application/json')
        else:
            return HttpResponseBadRequest()
    else:
       return HttpResponseNotAllowed(['POST'])
Shelled answered 11/1, 2012 at 17:52 Comment(3)
i get result success, but i don't see the file being saved on the path i set in the modal (it's local path:Users/yogevshelly/Downloads/) when i try just saving the image to disk using Image.save('path','JPEG') i see the file, but i have to add '/' to the path beginning. any ideas? thanksChristinachristine
Oops, the images were saved just fine, just in relation the project folder and not my computer's root folder, thanks a lot!Christinachristine
And don't forget to include enctype="multipart/form-data" in the form template as stated at https://mcmap.net/q/294677/-empty-request-files-with-django-upload-formsCuttlefish
M
7

Edit: Please use the answer chosen above - the code below works for the question but it is not recommended.

The image file you are uploading can be found in:

request.FILES['image'] # assuming input name is called 'image'

It does not return you an Image object, but rather a UploadedFile object. You can read this portion of the docs (I am assuming you are using Django 1.3.x): https://docs.djangoproject.com/en/1.3/topics/http/file-uploads/#handling-uploaded-files

It covers the fields and methods available in the UploadedFile object, and also a common way to handle file uploads manually. You can use the same method to write the image file to a file object and then saving it to your ImageField.

The following code should work, but it is not safe code. I am assuming you are using *nix machine, if not, save the destination file somewhere else.

@csrf_exempt
def saveImage(request):
    # warning, code might not be safe
    up_file = request.FILES['image']
    destination = open('/tmp/' + up_file.name , 'wb+')
    for chunk in up_file.chunks():
        destination.write(chunk)
    destination.close()
    img = someImage()
    img.image.save(up_file.name, File(open('/tmp/' + up_file.name, 'r')))
    img.save()
    # return any response you want after this

Other things to take note: Make sure you form has the following attribute for it to work:

 <form enctype="multipart/form-data" ... >

I don't recall this usage being normal, but really, Forms are recommended.

Mehetabel answered 11/1, 2012 at 16:35 Comment(2)
thanks, i know that. now what? what's the flow? do i save it to physical file and just pass the path to the imageField? any snippets it's should be a very common task, thanks!Christinachristine
I have updated the answer with sample code. The code would be much simpler and safer if you used Model Forms.Mehetabel

© 2022 - 2024 — McMap. All rights reserved.