0

I want to upload multiple images for each student using django rest framework. currently, Im only able to upload one image for each student, but I want to be able to upload multiple images for each student in uploads folder in a directory of their name. Im building a facial attendance recognition system and I need multiple images of each student. here is my models.py file.

class Student(models.Model):
    Name=models.CharField(max_length=200)
    Enrollment_No=models.CharField(max_length=200)
    Registration_No=models.CharField(max_length=200)
    Semester=models.IntegerField()
    Year=models.CharField(max_length=200)
    Course_Name=models.CharField(max_length=200)
    Course_Code=models.CharField(max_length=200)
    registered_at= models.DateField(auto_now_add=True)


    def __str__(self):
        return self.Name

class studentImage(models.Model):
    Name= models.CharField(max_length=200, default='no-name')
    Student= models.ForeignKey(Student, on_delete= models.CASCADE)
    image=models.ImageField(upload_to= 'uploads/')

    def __str__(self):
        return self.Name

class serializers.py file

class StudentSerializer(serializers.ModelSerializer):
    class Meta:
        model=Student
        fields="__all__"


class studentImageSerializer(serializers.ModelSerializer):
    class Meta:
        model= studentImage
        fields="__all__"

views.py file

@api_view(['POST'])
def studentCreate(request):
    serializer = StudentSerializer(data=request.data)
    if serializer.is_valid(raise_exception=True):
        serializer.save()
    else:
        print('Hello World')
    return Response(serializer.data)

Please let me know what changes should I make to the code, what I should add in the views file to allow multiple images upload of student in uploads directory in a directory of student name

habiba
  • 321
  • 3
  • 12

2 Answers2

1

so I finally figured to solve it. I added the below function to my student serializer

def create(self, validated_data):
       images_data = self.context.get('view').request.FILES
       student = studentImage.objects.create(name=validated_data.get('name', 'no-name'),
                                   )
       for image_data in images_data.values():
           studentImage.objects.create(student=student, image=image_data)
       return student

make sure to pass serializers.HyperlinkedModelSerializer as a parameter to student serializer

I added to my views.py file

class Upload(viewsets.ModelViewSet):
    serializer_class = StudentSerializer
    queryset = Student.objects.all()

and to the models.py file I added

def get_upload_path(instance, filename):
    return 'uploads/{0}/{1}'.format(instance.student.name, filename)
class studentImage(models.Model):
    student = models.ForeignKey(Student, on_delete=models.CASCADE)
    image = models.FileField(blank=True, upload_to=get_upload_path)
habiba
  • 321
  • 3
  • 12
  • yes you can also do that by overriding the def create(self, validated_data) method. thanks for updating us. – Sohaib Dec 30 '20 at 09:52
0

You an use nested serializer to save and retrieve multiple images against a student.

class serializers.py file

class studentImageSerializer(serializers.ModelSerializer):
    class Meta:
        model= studentImage
        fields="__all__"

class StudentSerializer(serializers.ModelSerializer):
    student_images = studentImageSerializer(many=True, write_only=True)
    class Meta:
        model=Student
        fields=('Name', 'Enrollment_No', 'Registration_No', 'Semester', 'Year', 'Course_Name', 'Course_Code', 'registered_at', 'student_images')
Sohaib
  • 566
  • 6
  • 15
  • hi I tried this but Im getting error in postman { "images": [ "This field is required." ] } – habiba Dec 30 '20 at 07:49
  • I have added the images field but still postman is telling me that { "images": [ "This field is required." ] } – habiba Dec 30 '20 at 07:50
  • yes you need to pass the **image** field and pass image file. because you added it in your studentImage model. Also try to pass **image** field not images. – Sohaib Dec 30 '20 at 08:18
  • hi thanks for replying Im doing that but still getting the same error. – habiba Dec 30 '20 at 08:43
  • https://stackoverflow.com/questions/48756249/django-rest-uploading-and-serializing-multiple-images I think I should be doing something like this, do you know how I can use the upload viewset – habiba Dec 30 '20 at 08:43