Skip to content

Instantly share code, notes, and snippets.

@yprez yprez/fields.py
Last active Oct 7, 2019

Embed
What would you like to do?
Django rest framework - Base64 image field
import base64
from django.core.files.base import ContentFile
from rest_framework import serializers
class Base64ImageField(serializers.ImageField):
def from_native(self, data):
if isinstance(data, basestring) and data.startswith('data:image'):
# base64 encoded image - decode
format, imgstr = data.split(';base64,') # format ~= data:image/X,
ext = format.split('/')[-1] # guess file extension
data = ContentFile(base64.b64decode(imgstr), name='temp.' + ext)
return super(Base64ImageField, self).from_native(data)
@juanchosaravia

This comment has been minimized.

Copy link

commented Jan 21, 2014

Thanks man!! You save my day!

@lensraster

This comment has been minimized.

Copy link

commented Nov 28, 2014

Thanks man! Exactly what I needed

@lensraster

This comment has been minimized.

Copy link

commented Nov 28, 2014

@s2krish

This comment has been minimized.

Copy link

commented Jul 29, 2015

from DRF 3.0, from_native is changed to to_internal_value http://www.django-rest-framework.org/topics/3.0-announcement/

@farhanali99

This comment has been minimized.

Copy link

commented Aug 28, 2015

What if i want to make the image optional?, if i don't provide the image it gives error "no file is attached"

@jyotman

This comment has been minimized.

Copy link

commented Aug 28, 2015

Hi please explain where do i use this code?

This is my serializers.py
class Image64Serializer(serializers.ModelSerializer):
class Meta:
model = SampleImage64
fields = ('id', 'image64')

This is models.py
class SampleImage64(models.Model):
image64 = models.ImageField(upload_to('images'))

@xtrinch

This comment has been minimized.

Copy link

commented Mar 4, 2016

And when I want to fetch that file? I get "http://some-ip/api/users/17/Raw%20content"

@rbtsolis

This comment has been minimized.

Copy link

commented Apr 13, 2016

Wuau this method is to convert base64 to image, thank you again, you save my day and my life :D

@icorradi

This comment has been minimized.

Copy link

commented Apr 13, 2016

@s2krish Thanks man! Your comment was useful for me!

@kevin-brown

This comment has been minimized.

Copy link

commented May 26, 2016

You can find a more up-to-date (compatible with 3.x) base64 image field in the following Stack Overflow answer.

Django REST Framework upload image: “The submitted data was not a file”

@arshdoda

This comment has been minimized.

Copy link

commented Mar 31, 2018

I have made this field optional. I want to pass null value to the field but its showing error

@darkhuntr

This comment has been minimized.

Copy link

commented Aug 13, 2019

@kevin-brown thanks, man! You save my day!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.