0

I am trying to send json response in django but I am getting this error

TypeError: Object of type File is not JSON serializable

Error is coming because I am using type <class 'django.core.files.base.File'> in json response. So how can I convert this to json serializable formate?

Code:

        user_id = User.objects.get(id=token_data['user_id'])
        all_posts = publicPost.objects.filter(user_id=user_id)
        post_ids = [] 
        for post in all_posts:
            post_ids.append(post.id)
        images = {} 
        for id in post_ids:
            img_obj =  PostImage.objects.filter(post_id=id) 
            imgs = [img_obj[0].image.file] 
            try:
                x = img_obj[0].other_image1.file
                imgs.append(x)
            except ValueError:
                pass
            try:
                x = img_obj[0].other_image2.file
                imgs.append(x)
            except ValueError:
                pass
            try:
                x = img_obj[0].other_image2.file
                print('type', type(x))
                imgs.append(x)
            except ValueError:
                pass 

            images[id] = imgs 
            
        return JsonResponse({'posts': post_ids, 'images': images})

2 Answers 2

1

Serialize the url, not the image:

img_obj[0].image.url

instead of

img_obj[0].image.file
Sign up to request clarification or add additional context in comments.

3 Comments

But I need to send images to react.js so I can't open the images in react.js if I do img_obj[0].image.url instead of img_obj[0].image.file
What stops you from doing <img src={image_url}/>?
This is the recommended way of doing this, because your images might be hosted elsewhere and you take the load off Django. Django is not meant to serve large files/images.
0

if you really need to send a file in a response you can try to convert it to bytes first.

images = [bytes(img).decode('utf8') for img in images]

3 Comments

I am getting this error now TypeError: Object of type bytes is not JSON serializable
edited, you also have to convert it to string
If you really want to do this approach, you should convert the image to base64 encoding. Not UTF-8.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.