1

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.

4
  • Is there a reason you don't explicitly specify the field title_picture in your FileListSerializer? I think you can just add it there and use that information as well in validated_data. Commented Nov 14, 2020 at 11:01
  • @physicalattraction thansk for your response. My validated_data only includes the image but not the title_picture. If i print the validated_data it 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. Commented Nov 14, 2020 at 18:03
  • With your current implementation you indeed have no field title_picture. What you need is to specify that in your serializer: title_picture = serializers.CharField(...) Commented Nov 14, 2020 at 18:37
  • than you now i can access the title_picture. I will post the answer when i have it. Commented Nov 14, 2020 at 21:04

0

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.