Tony Roczz
Tony Roczz

Reputation: 2398

Django save base64 string to filesystem using models.ImageField

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.

Upvotes: 5

Views: 5623

Answers (1)

Dalvtor
Dalvtor

Reputation: 3286

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)

Upvotes: 7

Related Questions