Django.fun

How do i upload multiple image file into single models using Django rest framework?

I am stuck to upload a multiple image file at duration of creating doctor model .. I think to implement multiple upload, you need to set the additional field for uploading in the DoctorSerializer.

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 doctor 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.

Models.py

class Doctor(models.Model):

def get_upload_path(instance, filename):
    return 'documents/{0}/{1}'.format(instance.name, filename)

mobile_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Up to 15 digits allowed.")
name = models.CharField(max_length=255, blank=False, null=False)
mobile = models.CharField(validators=[mobile_regex], max_length=15)
email = models.EmailField(max_length=255, blank=False, null=False)
picture = models.ImageField(upload_to="images/", blank=True, null=True)
document = models.FileField(upload_to=get_upload_path, null=True, blank=True)

and Here is my serializers.py

class DoctorSerializer(serializers.ModelSerializer):
class Meta:
    model = Doctor
    fields = ['id','name','email','mobile' ,'document',]
    
def create(self, validated_data):
    return Doctor.objects.create(**validated_data)

and my views.py file...

class CreateDoctorAPIView(APIView):
parser_classes = (MultiPartParser, )
def post(self,request,*args):
    try:
        files = request.FILES['document']
        print(files)
        serializer = DoctorSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response({
                'message': 'Doctor created successfully',
            })
        else:
            return Response({
                'message':'something wrong'
            })
    except Exception as e:
        return Response({
            'mesaage':str(e)
        })

You can do that by creating a separate table for images only and create a ManyToMany relation between them


class DoctorImage(models.Model):
    def get_upload_path(instance, filename):
        return 'documents/{0}/{1}'.format(instance.name, filename)
    
    picture = models.ImageField(upload_to="images/", blank=True, null=True)


class Doctor(models.Model):

    mobile_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Up to 15 digits allowed.")
    name = models.CharField(max_length=255, blank=False, null=False)
    mobile = models.CharField(validators=[mobile_regex], max_length=15)
    email = models.EmailField(max_length=255, blank=False, null=False)
    doctor_images = models.ManyToManyField(DoctorImage)
    document = models.FileField(upload_to=get_upload_path, null=True, blank=True)

In your serializers.py

class DoctorSerializer(serializers.ModelSerializer):
    class Meta:
        model = Doctor
        fields = ['id','name','email','mobile' ,'document',]
    
    def create(self, validated_data):
        # assuming you're sending images in a list
        images = validated_data.pop('images') # this is your key name that you'll send in request
        doctor = Doctor.objects.create(**validated_data)
        doctor.docter_images.add(*images) # pass images list at once
        return doctor

Tutorials

Константы Python: Улучшение управляемости вашего кода

Современный Python: начинаем проект с pyenv и poetry

Настройка проекта Python — виртуальные среды и управление пакетами

Использование requests в Python — тайм-ауты, повторы, хуки

Понимание декораторов в Python

ProcessPoolExecutor в Python: полное руководство

map() против submit() с ProcessPoolExecutor в Python

Понимание атрибутов, словарей и слотов в Python

Полное руководство по slice в Python

Выпуск Django 4.0

Безопасное развертывание приложения Django с помощью Gunicorn, Nginx и HTTPS

Автоматический повтор невыполненных задач Celery

Django REST Framework и Elasticsearch

Докеризация Django с помощью Postgres, Gunicorn и Nginx

Асинхронные задачи с Django и Celery

Релизы безопасности Django: 3.2.4, 3.1.12 и 2.2.24

Выпуски исправлений ошибок Django: 3.2.3, 3.1.11 и 2.2.23

Эффективное использование сериализаторов Django REST Framework

Выпуски безопасности Django: 3.2.2, 3.1.10 и 2.2.22

Выпущенные релизы безопасности Django: 3.2.1, 3.1.9 и 2.2.21

View all tutorials →