0

Trying to do a fairly simple project where I can upload multiple images to my server with just a few other fields. I tried to follow this post but wasn't able to get anywhere on it. I know I am going to need to break my models into two with 'PostImage' having a ForeignKey that relates to Post. And I know I will need to modify the serializer in order to allow an array of image files. Any help would be greatly appreciated.

models.py:

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length = 100)
    content = models.TextField()
    image = models.ImageField(upload_to='post_images')

    def __str__(self):
        return self.title

serializers.py:

from rest_framework import serializers
from .models import Post

class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = '__all__'

views.py:

from django.shortcuts import render

# Create your views here.

from .serializers import PostSerializer
from .models import Post
from rest_framework.views import APIView
from rest_framework.parsers import MultiPartParser, FormParser
from rest_framework.response import Response
from rest_framework import status
# Create your views here.

class PostView(APIView):
    parser_classes = (MultiPartParser, FormParser)

    def get(self, request, *args, **kwargs):
        posts = Post.objects.all()
        serializer = PostSerializer(posts, many=True)
        return Response(serializer.data)

    def post(self, request, *args, **kwargs):
        posts_serializer = PostSerializer(data=request.data)
        if posts_serializer.is_valid():
            posts_serializer.save()
            return Response(posts_serializer.data, status=status.HTTP_201_CREATED)
        else:
            print('error', posts_serializer.errors)
            return Response(posts_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
iHusk
  • 13
  • 6
  • What difficulty you are facing to implement? You need to send data in **`form/multipart`** content type or similar `form` supported format – JPG Feb 03 '20 at 03:06
  • @ArakkalAbu I am sending it it "'content-type': 'multipart/form-data'". When implementing the solution from the above Stack Overflow I don't get any image submitted to the server nor can I select multiple pictures – iHusk Feb 03 '20 at 03:39
  • Any errors have you got? – JPG Feb 03 '20 at 03:43
  • @ArakkalAbu Works perfect for one image above, once implementing the solution from teh other post I get a 500 error when posting to the server, no errors in django though – iHusk Feb 03 '20 at 04:19
  • Also will only let me select one file – iHusk Feb 03 '20 at 04:20

1 Answers1

0

You need to have the ForeignKey relation with the Post Model. You can do like this:

models.py

from django.db import models

class Media(models.Model):
    detail = models.CharField(max_length=200, default='', null=True, blank=True)
    user = models.ForeignKey(to=MyUser, related_name='user_media')
    type = models.CharField(max_length=20, choices=Constant.model.MEDIA_TYPE, default='other')
    media = models.FileField(max_length=10000, upload_to=upload_media_file, blank=True, null=True)

class Post(models.Model):
    title = models.CharField(max_length = 100)
    content = models.TextField()
    media = models.ForeignKey(Media, related_name='posts')

    def __str__(self):
        return self.title

serializer.py

from rest_framework import serializers
from .models import Post

class PostSerializer(serializers.ModelSerializer):
    media = serializers.ListField(write_only=True,
                                  child=serializers.FileField(max_length=10000000,
                                                              allow_empty_file=True,
                                                              use_url=False)
    class Meta:
        model = Post
        fields = '__all__' 

    def is_valid(self, raise_exception=False):
            if len(data.getlist('media')) > 5:
                 raise 'some error'
Mirza715
  • 420
  • 5
  • 15
  • 1
    This isn't working. I feel like this is missing something. I left out user and detail in the Media class. But where do you get 'Constant' as choices? At the end of the day what I am looking for is to upload the multiple images to the server and then have an array of file locations when I request it through the api. – iHusk Feb 04 '20 at 23:17
  • Contant is just the placement for the choices that you can replace. This code will upload multiple images to the server. – Mirza715 Feb 05 '20 at 12:24