Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
505 views
in Technique[技术] by (71.8m points)

django rest api framework "list" obj has no attribute values

I trying to pass some files through djangorest framework and while trying to do so, I am facing error

'list' object has no attribute 'name'

my views.py

from django.shortcuts import render
from rest_framework import serializers
from rest_framework import viewsets
from rest_framework import status
from rest_framework.response import Response

from restfilesupload.serializers import FileSerializer


class FileUploadViewSet(viewsets.ViewSet):

    def create(self, request):

        serializer_class = FileSerializer(data=request.data)
        if request.method == 'POST':
            if 'file' not in request.FILES or not serializer_class.is_valid():
                return Response(status=status.HTTP_400_BAD_REQUEST)
            else:
                handle_uploaded_file(request.FILES.getlist("file"))
                return Response(status=status.HTTP_201_CREATED)


    def handle_uploaded_file(f):
      with open(f.name, 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)

    class Meta:
        fields = ['pk' , 'file']

my serializers.py

from rest_framework import serializers


class FileSerializer(serializers.Serializer):
    file = serializers.FileField(max_length=None, allow_empty_file=False)

My error :

enter image description here

Here is the github repo for the project ..

github

where currently I can upload single file just fine but the problem arises while trying to upload multiple images


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From official Django 3.1 documentation: HttpRequest.FILES

A dictionary-like object containing all uploaded files. Each key in FILES is the name from the . Each value in FILES is an UploadedFile.

From official Django 3.1 documentation: QueryDict.getlist(key, default=None)

Returns a list of the data with the requested key. Returns an empty list if the key doesn’t exist and default is None. It’s guaranteed to return a list unless the default value provided isn’t a list.

Your problem is in this line:

handle_uploaded_file(request.FILES.getlist("file"))

Try

handle_uploaded_file(request.FILES['file'])


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...