#DRF - I want to Upload multiples images in DRF

9 messages · Page 1 of 1 (latest)

charred ermine
#

guys, i need some help, i wanted to create a api where user can upload multiple images.
Here is my db

from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.translation import gettext_lazy as _

# Defining a custom user model so we can making any changes in the future to this model
# without causing any conflicts with database.
class CustomUserModel(AbstractUser):
    email = models.EmailField(_("Email"), unique=True, blank=False, null=False)

class Project(models.Model):
    """Project database to store projects name with images relative table"""
    name = models.CharField(max_length=120)
    created_on = models.DateTimeField('Project Created', auto_now_add=True)

    def __str__(self):
        return self.name  
    
class Image(models.Model):
    project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='images')
    image = models.ImageField(upload_to="images")
#

Serializers.py

class ProjectDetailSerializer(serializers.ModelSerializer):
    images = ProjectImageSerializer(many=True, read_only=True)

    class Meta:
        model = Project
        fields = ('id', 'name', 'images')


class ImageUploadSerializer(serializers.ModelSerializer):
    images = ProjectImageSerializer(many=True, read_only=True)
    uploaded_images = serializers.ListField(
        child=serializers.ImageField(allow_empty_file=False, use_url=False),
        write_only=True
    )

    class Meta:
        model = Project
        fields = ["id", "images", "uploaded_images"]

    def create(self, validated_data):
        uploaded_images = validated_data.pop("uploaded_images")
        project_id = self.context.get('project_id')

        try:
            project = Project.objects.get(pk=project_id)
        except Project.DoesNotExist:
            raise serializers.ValidationError('Project not found')

        for image in uploaded_images:
            Image.objects.create(project=project, image=image)

        return project

what i am having problem is, how go i provide the ImageUploadSerializer the project id?
I want to upload images so that they can be send in the database with an existing Project database foreign key.
For example- i have many projects created with different name and id's, now, i want to upload images to a database with relation to a project as in my image db, project is a relation key. How do i provide a relation key.

I tried the above code and tested with postman, but everytime i was getting a error 400 BAD REQUEST

charred ermine
#
class ImageView(generics.CreateAPIView):
    serializer_class = ImageUploadSerializer
    parser_class = [MultiPartParser, FormParser]
charred ermine
#

DRF - I want to Upload multiples images in DRF

gray jolt
#

how go i provide the ImageUploadSerializer the project id?

Your 'Image' class seems to do the trick of relating an image to a project.

charred ermine
#

solved it with this

#
class ImageUploadSerializer(serializers.ModelSerializer):
    images = ProjectImageSerializer(many=True, read_only=True)
    uploaded_images = serializers.ListField(
        child=serializers.ImageField(allow_empty_file=False, use_url=False),
        write_only=True
    )

    class Meta:
        model = Image
        fields = ["id", "project", "images", "uploaded_images"]

    def create(self, validated_data):
        uploaded_images = validated_data.pop("uploaded_images")
        project_id = self.initial_data['project']

        try:
            project = Project.objects.get(pk=project_id)
        except Project.DoesNotExist:
            raise serializers.ValidationError('Project not found')

        for image in uploaded_images:
            print(image)
            test = Image.objects.create(project=project, image=image)

        return test
gray jolt
#

this is awesome... I'm not here on my own project yet but I might need this later for reference.

Just to be clear, this allows you to upload multiple images and associate them all with a project?