-
-
Save yprez/7704036 to your computer and use it in GitHub Desktop.
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) |
How about using uuids for file names? https://gist.github.com/lensraster/24de2ba061989d70ff4e#file-fields-py
from DRF 3.0, from_native
is changed to to_internal_value
http://www.django-rest-framework.org/topics/3.0-announcement/
What if i want to make the image optional?, if i don't provide the image it gives error "no file is attached"
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'))
And when I want to fetch that file? I get "http://some-ip/api/users/17/Raw%20content"
Wuau this method is to convert base64 to image, thank you again, you save my day and my life :D
@s2krish Thanks man! Your comment was useful for me!
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”
I have made this field optional. I want to pass null value to the field but its showing error
@kevin-brown thanks, man! You save my day!
Thanks man! Exactly what I needed