1👍
The CreateModelMixin
of the CreateAPIView
calls the serializer listed. Therefore, you need to serialize and validate the image inside the AnnouncementSerializer
using the PhotoSerializer
. This can be done by overriding the create
method of the AnnouncementSerializer
:
class AnnouncementSerializer(serializers.ModelSerializer):
parameters = ParameterSerializer(many=True, required=False)
photo = PhotoSerializer(
many=True,
required=False,
read_only=True) # Set read_only to True
class Meta:
model = Announcement
fields = ['id', 'name', 'address', 'date',
'price', 'description', 'author', 'parameters', 'photo']
def create(self, validated_data):
"""
Serializes an image if it has been uploaded, then passes the image
back to the validated_data to finish creating the Announcement.
"""
image_data = self.context['request'].FILES
if image_data:
serializer = PhotoSerializer(data=image_data)
serializer.is_valid(raise_exception=True)
image = serializer.save()
validated_data['image'] = image
return super().create(validated_data)
That should be all you have to do.
Source:stackexchange.com