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
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")
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With