Reputation: 501
I am getting this error Object of type ProductImage is not JSON serializable
I am trying to make model in which I can add multiple images using ManytoManyFeild().and I then I want to serialize it so that I can send it to and show on frontend page.
here is my models:
from django.db import models
class Product(models.Model):
id = models.IntegerField(unique=True,primary_key=True)
title = models.CharField(max_length=200)
description = models.TextField(max_length= 100000 ,null=True, blank=True)
price = models.FloatField()
count = models.IntegerField(default=1)
file_content = models.ManyToManyField("ProductImage", related_name='file_content', blank=True, null=True)
offer= models.BooleanField(default=False)
def __str__(self):
return self.title
class ProductImage(models.Model):
property_id = models.ForeignKey(Product,on_delete=models.CASCADE ,null=True, blank=True)
media = models.FileField(upload_to='pics')
def __str__(self):
return '%s-image' % (self.property_id.title)
and here is my serializer.py:
from rest_framework import serializers
from . models import Product, ProductImage
class ProductImageSerializer(serializers.ModelSerializer):
class Meta:
model = ProductImage
fields = [ 'property_id','media']
class ProductSerializer(serializers.ModelSerializer):
file_content = ProductImageSerializer(many=True)
class Meta:
model = Product
fields = ['id', 'title','description', 'price','count', 'file_content',
'offer']
extra_kwargs = {
"file_content": {
"required": False,
}
}
and here is my Views.py:
from rest_framework.serializers import Serializer
from . models import Product, ProductImage
from rest_framework.response import Response
from . serializer import ProductSerializer
from rest_framework import status
from rest_framework.parsers import MultiPartParser, FormParser
from rest_framework.decorators import api_view, permission_classes, parser_classes
from rest_framework.permissions import IsAuthenticated
@api_view(['POST','GET'])
@permission_classes([IsAuthenticated])
@parser_classes([MultiPartParser, FormParser])
def ProductViews(request):
if request.method == 'POST':
files = request.FILES.getlist('file_content')
if files:
request.data.pop('file_content')
serializer = ProductSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
tweet_qs = Product.objects.get(id=serializer.data['id'])
uploaded_files = []
for file in files:
content = ProductImage.objects.create(media=file)
uploaded_files.append(content)
tweet_qs.file_content.add(*uploaded_files)
context = serializer.data
context["file_content"] = [file.id for file in uploaded_files]
return Response(context, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
else:
serializer = ProductSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
context = serializer.data
return Response(context, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
elif request.method == 'GET':
detail = [{"title": detail.title, "id": detail.id, "count": detail.count, "description": detail.description, "price": detail.price, "offer": detail.offer , "details": detail.file_content.all()}
for detail in Product.objects.all()]
return Response(detail)
I don't what's wrong so I will be very grateful to you if can help. Thanks
Note:If you know any other better way to make a Json that can include a list of images, you can also share it(or its link).
Upvotes: 1
Views: 1348
Reputation: 21
This may help you:
class ProductImage(models.Model):
property_id = models.ForeignKey(Product, on_delete=models.CASCADE ,null=True, blank=True)
media = models.FileField(upload_to='pics')
def __str__(self):
return '%s-image' % (self.property_id.title)
def media_url(self):
return self.media.url
class ProductImageSerializer(serializers.ModelSerializer):
class Meta:
model = ProductImage
fields = [ 'property_id','media','media_url']
Upvotes: 1