K. Valentin K. Valentin - 17 days ago 10
Python Question

How to serialize empty ImageField to JsonResponse?

I have a model:

class Item(models.Model):
title = models.TextField(verbose_name='Title', default='Default title')
photo = models.ImageField(verbose_name='Photo',upload_to='media/',blank=True)

def __str__(self):
return self.title


I am trying to serialize this model object to JSON response for the frontend. This is my test view:

from app.models import Item
from django.forms.models import model_to_dict
from django.http import JsonResponse

def get(self, request, *args, **kwargs):
item_object = Item.objects.first()
to_json = model_to_dict(item_object)
return JsonResponse(to_json)


When i created Item object without photo field (from django shell without downloading real file, this field isn't nessesary), JsonResponse throws TypeError: is not JSON serializable

[16/Nov/2016 13:51:15] "GET /items/?item_id=9&shop_id=4 HTTP/1.1" 500 129160
Internal Server Error: /items/
Traceback (most recent call last):
File "/home/lamberk/python/picasel/rc_cross_upsell/venv/lib/python3.5/site-packages/django/core/handlers/exception.py", line 39, in inner
response = get_response(request)
File "/home/lamberk/python/picasel/rc_cross_upsell/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/lamberk/python/picasel/rc_cross_upsell/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/lamberk/python/picasel/rc_cross_upsell/venv/lib/python3.5/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/home/lamberk/python/picasel/rc_cross_upsell/venv/lib/python3.5/site-packages/django/views/generic/base.py", line 88, in dispatch
return handler(request, *args, **kwargs)
File "/home/lamberk/python/picasel/rc_cross_upsell/CrossUpsell/apps/items/views.py", line 54, in get
'up_sells': up_sells,
File "/home/lamberk/python/picasel/rc_cross_upsell/venv/lib/python3.5/site-packages/django/http/response.py", line 520, in __init__
data = json.dumps(data, cls=encoder, **json_dumps_params)
File "/usr/lib/python3.5/json/__init__.py", line 237, in dumps
**kw).encode(obj)
File "/usr/lib/python3.5/json/encoder.py", line 198, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python3.5/json/encoder.py", line 256, in iterencode
return _iterencode(o, 0)
File "/home/lamberk/python/picasel/rc_cross_upsell/venv/lib/python3.5/site-packages/django/core/serializers/json.py", line 118, in default
return super(DjangoJSONEncoder, self).default(o)
File "/usr/lib/python3.5/json/encoder.py", line 179, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <ImageFieldFile: None> is not JSON serializable

Answer

I would suggest using custom JSON encoder, something along those lines:

class CustomEncoder(DjangoJSONEncoder):
    def default(self, obj):
        if isinstance(obj, ImageFieldFile):
            # Do whatever appropriate for your case, like returning None
        return super(LazyEncoder, self).default(obj)

And use it like this:

return JsonResponse(to_json, encoder=CustomEncoder)
Comments