Multiple file upload with reactjs form and Django backend not working

I created backend to upload multiple images with some text and multiple documents using django rest framework. I tested the backend with postman and upload works fine! when i upload files with react form, backend throws error with request.FILES empty.

I am using React 17.0.2 version and next 12.0.4 Django version is 3.2.14 and rest-framework version is 3.13.1

Below is the code of react submit form. i am able to see the files in the console is submit form handler.

const submitForm = async e => {
    const formData = new FormData()
    formData.append('images', e.formData.images)

    formData.append('docs', e.formData.req_doc)

    formData.append('description', e.formData.description)
    let url = 'http://localhost:3000/requirement/requirements/'
    fetch(url, {
        method: 'POST',
        headers: {
            Accept: '*/*',
            'Accept-Encoding': 'gzip, deflate, br',
            content_type: 'multipart/form-data; boundary=<calculated when request is sent>'
        body: formData
    }).then(function (response) {

i am also attaching the screenshot of request from browser which shows the images and files being sent in request.

The Django backend code where error occurs is below.

class RequirementSerializer(serializers.ModelSerializer):
    images = RequirementImageSerializer(many=True, required=False)
    requirement_files = RequirementDocSerializer(many=True, required=False)
    class Meta:
        model = Requirement
        fields = ['id', 'name','description', 'email', 'mobile', 'city', 'created_at', 'updated_at','images','requirement_files']

    # def validate_name(self,value):                                                
    #     if(value == "sumit"):
    #         raise serializers.ValidationError("name cant be sumit")
    #     return value
    def validate(self,data):
        pprint ((self.context['request'].FILES))
        images_data = dict((self.context['request'].FILES).lists()).get('images', None)
        docs_data = dict((self.context['request'].FILES).lists()).get('docs', None)
        print("images data below")
        for image in images_data:
            if(not validateSize(image,allowedImageSize)): 
                raise serializers.ValidationError("Image size should be below 50 MB ")
            if(not validateFileType(image,allowedImageTypes)):
                raise serializers.ValidationError(" Only image types .png, .jpg and .jpeg allowd ")
        for doc in docs_data:
            if(not validateSize(doc,allowedDocSize)): 
                raise serializers.ValidationError("requirement document size should be below 50 MB ")
            if(not validateFileType(doc,allowedRequirementTypes)):
                raise serializers.ValidationError(" requireent doc should be only pdf,doc, and docx  ")
        return data;
    def create(self, validated_data):     
        print('came in create ')   
        requirement = Requirement.objects.create(**validated_data)
        # try to get and save images (if any)
        images_data = dict((self.context['request'].FILES).lists()).get('images', None)
        # try:
        images_data = dict((self.context['request'].FILES).lists()).get('images', None)
                for image in images_data:
                    RequirementImage.objects.create(requirement=requirement, image=image)
                    # imgOb = RequirementImage(requirement=requirement,image=image)
                    # serial = RequirementImageSerializer(data={"requirement":requirement,"image":image})
                    # if(serial.is_valid()):
                    #     print("RequirementImageSerializer is valid")
                    #     RequirementImage.objects.create(requirement=requirement, image=image)
                    # else:
                    #     print("RequirementImageSerializer says invalid")
                    #     print(serial.errors)
            except Exception as e:
                docs_data = dict((self.context['request'].FILES).lists()).get('docs', None)
                for doc in docs_data:
                    RequirementDoc.objects.create(requirement=requirement, requirement_file=doc)
            except Exception as e:
            print("Data not validated")
        return requirement

class RequirementImageSerializer(serializers.ModelSerializer):
    image = serializers.ImageField()
    class Meta:
        model = RequirementImage
        fields = ['id', 'image', 'requirement']
    extra_kwargs = {
        'requirement': {'required': False},
class RequirementDocSerializer(serializers.ModelSerializer):
    class Meta:
        model = RequirementDoc
        fields = ['id', 'requirement_file', 'requirement']
    extra_kwargs = {
        'requirement': {'required': False},

This is screenshot of django console error.

The dictionary pprint ((self.context['request'].FILES)) is coming empty when i upload from react but it works perfectly fine and code uploads all data when i send request from postman.

Back to Top