K
K
Klaus Kater2015-08-16 21:15:48
Django
Klaus Kater, 2015-08-16 21:15:48

How to make a file field in django rest framework?

Hello, there was a problem, Google did not help (
There is a model with a file, and I'm trying to upload a file there.

class File(models.Model):
    owner = models.ForeignKey('auth.User', verbose_name=u'Владелец')
    name = models.CharField(verbose_name=u'Название', max_length=1000, null=True, blank=True)
    file = models.FileField(verbose_name=u'Документ', upload_to=get_file_path)

class FileSerializer(serializers.ModelSerializer):
    owner = UserSerializer(read_only=True)
    file = serializers.FileField()

    class Meta:
        model = File
        fields = ('owner', 'file') 


class ViewSet(viewsets.GenericViewSet):
    @list_route(methods=['post'])
    def load_file(self, request):
        file_tmp = request.data.get('file')
        if not file_tmp:
            return Response("Нет файла, или неправильный формат", status=status.HTTP_400_BAD_REQUEST) 

        serializer = FileSerializer(request.user, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=201)
        return Response(serializer.errors, status=400)

The problem is in the error:
InMemoryUploadedFile object has no attribute url

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey, 2015-08-16
@kurojneko

I suspect that you need to register an appropriate parser for your ViewSet - multipart or fileupload .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question