Suppose I have an application to deal with some mail messages with images.
I am not sure how serializer can help me to create an mail object and all related images at the same time (because mail and images belong to different model as mentioned below)
Here are my related codes, sorry that I removed some fields from my actual model to help focus on this question's situation.
models.py
class Mail(models.Model):
id = models.AutoField(primary_key=True)
title = models.CharField(max_length=255)
content = models.CharField(max_length=255)
class MailImage(models.Model):
image = models.ImageField(upload_to=get_file_path, blank=True, null=True)
mail = models.ForeignKey(Mail, related_name='images')
serializers.py
class MailImageSerializer(serializers.ModelSerializer):
class Meta:
model = MailImage
class MailSerializer(serializers.ModelSerializer):
# images = ??? //Can any one help on this?
class Meta:
model = Mail
APIView
class SentMailView(APIView):
permission_classes = ()
parser_classes = (FileUploadParser,)
def post(self, request, format=None):
data = {
'images': request.data['images'],
'title': request.data['title'],
'content': request.data['content'],
}
serializer = MailSerializer(data=data)
if serializer.is_valid():
serializer.save()
return Response({'success': True})
else:
return Response({'success': False})
cURL Testing
curl -X POST -H "Content-Type:multipart/form-data" -F "title=test" -F "content=test" -F "images=@Testing.jpg" http://127.0.0.1:8000/api/sent-mail
Also this cURL command only send one picture, it would be appreciate if anyone can revise it to send multiple images for an mail in ONE cURL command.
Thanks for helping.