4

Background: I have an Article model storing some articles and each article can have multiple images. I need to design an api to create an article and the corresponding images if necessary. But I have no ideas of how to make the images can be also created at the same time.

models.py

class Article(models.Model):
    id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=50)
    content = models.CharField(max_length=255) 
    def __unicode__(self):
        return self.title

class ArticleImage(models.Model):
    id = models.AutoField(primary_key=True)
    image = models.ImageField(upload_to=get_file_path, blank=True, null=True)
    article = models.ForeignKey(Article)

serializers.py

class ArticleImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = ArticleImage

class ArticleSerializer(serializers.ModelSerializer):
    #images = ???
    class Meta:
        model = Article

api.py

class ArticleView(APIView):
    def post(self, request, format=None):
        try:
            serializer = ArticleSerializer(request.data)
            if serializer.is_valid():
                serializer.save()
                return Response({'success': True})
            else:
                return Response({'success': False})
        except:
            return Response({'success': False})

Request JSON

{  
   "title":"Sample Title",
   "content":"Sample Content",
   "images":[  
      "paul.jpg",
      "ada.jpg"
   ]
}

Thanks for help.

3
  • Is the jpg image data included in json/post somehow? Otherwise where will the images come from? Commented May 18, 2015 at 4:23
  • Yes, the image is included. The request json is a sample of the data structure for anyone's reference and actually when calling the api, the Content-Type should be "multipart/form-data". Thanks for your reply. Commented May 18, 2015 at 6:00
  • Anyone help for this question? Many thanks. Commented Jun 1, 2015 at 14:58

1 Answer 1

2

Assuming you're using DRF v3, you can find the answer to your question under the "Writable nested representations" section of the official docs on "Serializers".

Let me know if you need more help.

Sign up to request clarification or add additional context in comments.

Comments

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.