5

I am trying to upload image to file system using python django. I dont have any idea on how to proceed further.

in my model.py:

Class Test(object):
    mission = models.TextField(blank=True)
    image = models.ImageField(upload_to='documents/images/',blank=True)
    account = models.OneToOneField(Account, related_name='account')

in my view.py

def add_image(request, account):
    req = get_request_json(request)
    data = Test.objects.add_image(account, req)

in my manager.py

Class TestManager(models.Manager):
    def add_image(self, account, input):
        acc = self.get(account=account)
        acc.save()

        return acc;

But I am not sure how to proceed from here.

I would like to know how to save the base64 image string to the specified location and store the path/file name in database?

I have worked with python where I write the files to a directory and get the path and store in db. Here I want to use the django options.

I have to repeat the same process with other file formats too.

Tony Roczz
  • 2,366
  • 6
  • 32
  • 59

1 Answers1

7

If you have an image in base64 string format and you want to save it to a models ImageField, this is what I would do

import base64
from django.core.files.base import ContentFile

image_b64 = request.POST.get('image') # This is your base64 string image
format, imgstr = image_b64.split(';base64,')
ext = format.split('/')[-1]
data = ContentFile(base64.b64decode(imgstr), name='temp.' + ext)

Now, you can simply do

Test.objects.create(image=data)
Luiz
  • 1,985
  • 6
  • 16
Dalvtor
  • 3,160
  • 3
  • 21
  • 36
  • I am getting this error `string argument should contain only ASCII characters` in this line `data = ContentFile(base64.b64decode(imgstr), name='temp.' + ext)` – Tony Roczz Sep 28 '17 at 04:52
  • if removed `base64.b64decode` and using `data = ContentFile(imgstr, name='temp.' + ext)` this error occurs ` is not JSON serializable` – Tony Roczz Sep 28 '17 at 05:46
  • @Dalvtor, is it possible to do that using model form instance like. `form = UploadPicForm() ` then `form.image = data` – squal Jan 07 '19 at 09:00