Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I serialize an ImageField in Django?

I'm trying to serialize one of my models which has an ImageField. The inbuilt serializer can't seem to serialize this and therefore I thought of writing a custom serializer. Could you tell me how I could serialize an image and use this with the default JSON serializer in Django?

Thanks

like image 656
Mridang Agarwalla Avatar asked Dec 13 '22 09:12

Mridang Agarwalla


2 Answers

I wrote an extension to the simplejson encoder. Instead to serializing the image to base643, it returns the path of the image. Here's a snippet:

def encode_datetime(obj):
    """
    Extended encoder function that helps to serialize dates and images
    """
    if isinstance(obj, datetime.date):
        try:
            return obj.strftime('%Y-%m-%d')
        except ValueError, e:
            return ''

    if isinstance(obj, ImageFieldFile):
        try:
            return obj.path
        except ValueError, e:
            return ''

    raise TypeError(repr(obj) + " is not JSON serializable")
like image 102
Mridang Agarwalla Avatar answered Dec 30 '22 14:12

Mridang Agarwalla


you can't serialize the object, because it's an Image. You have to serialize the string representation of it's path.

The easiest way of achiving it is to call it's str() method when you what to serialize it.

json.dumps(unicode(my_imagefield)) # py2
json.dumps(str(my_imagefield)) # py3

should work.

like image 31
Rômulo Collopy Avatar answered Dec 30 '22 14:12

Rômulo Collopy