Creating an Image with Foreign Key to model instance does not return Image URL in serializer.data

I have two models that are connected through a foreign key. An article can have 0, 1 or many images. Both height_field and width_field are autocalculated. is_title_image is set in the POST request.

class Article(models.Model):
    slug = models.SlugField(null=True, default=None, unique=True, max_length=255)
    heading = models.CharField(max_length=2550)
    summary = models.CharField(max_length=25500)

class Image1(models.Model):
    height_field=models.PositiveIntegerField(default=0)
    width_field=models.PositiveIntegerField(default=0)
    file = models.ImageField(storage=PublicMediaStorage(), height_field='height_field', width_field='width_field')
    is_title_image = models.BooleanField(default=False)
    article = models.ForeignKey(Article, related_name='images', null=True, on_delete=models.DO_NOTHING)

First I create the article in the DraggableArticleSerializer and use the pk to create the images. Here I am not sure, if this is the optimal way. I use the ImageSerializer to receive all fields from the image instance. Article and image are both being created correctly in the db. But I am not able to use that data in the views.py in order to return it to the frontend. The images property is empty in serializer.data, and serializer.validated_data just returns the input InMemoryUploadedFile:

serializer.validated_data['images'][0]['file'] returns OrderedDict([('file', <InMemoryUploadedFile: husky4.jpg (image/jpeg)>), ('is_title_image', True)])

I dont know how my view should be changed from the regular CreateAPIView. Do I have to give some extra data to serializer.save() or is my problem located somewhere else.

class DraggableArticleSerializer(serializers.ModelSerializer):
     images = ImageSerializer(many=True, required=False)
     class Meta:
         model = Article
         fields = (
            "slug",
            "heading",
            "summary",
         )
    def create(self, validated_data):
        image_data=validated_data.pop("images")
        article = Article.objects.create(**validated_data)
        for image_entry in image_data:
             image_inputs = data={"file": image_entry['file'], "is_title_image":                                        
             image_entry['is_title_image'],  "article": article.pk}
             serializer = ImageSerializer(data=image_inputs, context=self.context)
             if serializer.is_valid():
                  serializer.save()
        return article
class ImageSerializer(serializers.ModelSerializer):
    file = serializers.FileField( max_length=100000,
                                         allow_empty_file=False)
        fields = (
            "pk",
            "file",
            "get_absolute_url",
            "url",
            "height_field",
            "width_field",
            "is_title_image",
        )
Back to Top