How to save image using django imageField?

publication from the application (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 a presentation? he receives the image in the mail request. Every thing I find is associated with a form (new to server)

+6
source share
2 answers

Just because you are not using the actual HTML form to submit data, this does not mean that you cannot use 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']) 
+15
source

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

Downloadable image file can be found in:

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

It does not return an Image object, but rather an UploadedFile object. You can read this part of the docs (I assume 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, as well as a general way to handle file uploads manually. You can use the same method to write an image file to an object file, and then save it to your ImageField.

The following code should work, but it is not safe code. I assume you are using a * 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 notes: make sure you have the following attribute:

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

I do not remember that this use was normal, but in fact it is recommended to use forms.

+3
source

Source: https://habr.com/ru/post/905730/


All Articles