I want to post an array of objects via the Django DRF. The array comes from my React JS frontend and contains a file and other data:
[{"image":"file object", "title_picture":"false"}, {"image":"file object", "title_picture":"true"},{"image":"file object", "title_picture":"false"}}
I get the image via a FileFild and the title_picture via a CharField, with the code below (following this approach) I can post a image list, but I lose the title_picture i.e., i get something like that [{"image":"file object",}, {"image":"file object",}, {"image":"file object"}]
###Model###
class Photo(models.Model):
image = models.FileField(upload_to='audio_stories/')
title_picture = models.CharField(max_length=100, null=True, default='some_value')
###Serializer###
class FileListSerializer (serializers.Serializer):
image = serializers.ListField(
child=serializers.FileField( max_length=1000,
allow_empty_file=False,
)
)
def create(self, validated_data):
image=validated_data.pop('image')
for img in image:
photo=Photo.objects.create(image=img)
return photo
###View###
class PhotoViewSet(viewsets.ModelViewSet):
serializer_class = FileListSerializer
parser_classes = (MultiPartParser, FormParser,)
http_method_names = ['post', 'head']
queryset=Photo.objects.all()
Basically my question is how to post an array (list) of objects if these objects contain a file and some other data.
title_picturein yourFileListSerializer? I think you can just add it there and use that information as well invalidated_data.validated_dataonly includes the image but not thetitle_picture. If i print thevalidated_datait only contains the file{'image': [<InMemoryUploadedFile: 3.jpeg (image/jpeg)>]}so i can not access the addtional data. I assume it gets blocked by the pre filtering of the file filed.title_picture. What you need is to specify that in your serializer:title_picture = serializers.CharField(...)