Chickenfresh
Chickenfresh

Reputation: 365

django rest fileupload with link returned

I was searching through stackoverflow for example of working fileupload APIView (using DRF of latest versions), I've already tried with many different code samples but none worked (some of them are deprecated, some - isn't what i want)

I have these models:

class Attachment(models.Model):
    type = models.CharField(max_length=15, null=False)
    attachment_id = models.CharField(max_length=50, primary_key=True)
    doc = models.FileField(upload_to="docs/", blank=True)

I don't wanna use forms and anything else but rest parsers I want to get POST'ed fields (for example name) in future

I believe the solution is easy but this doesnt work

class FileUploadView(APIView):
    parser_classes = (FileUploadParser,)

    def post(self, request):
        file_obj = request.FILES
        doc = Attachment.objects.create(type="doc", attachment_id=time.time())
        doc.doc = file_obj
        doc.save()
        return Response({'file_id': doc.attachment_id}, status=204)

Upvotes: 0

Views: 47

Answers (1)

JPG
JPG

Reputation: 88429

removing parser_class will solve almost all problems here. Try the following snippet

class FileUploadView(APIView):

    def post(self, request):
        file = request.FILES['filename']
        attachment = Attachment.objects.create(type="doc", attachment_id=time.time(), doc=file)
        return Response({'file_id': attachment.attachment_id}, status=204)


Screenshot of POSTMAN console
enter image description here

Upvotes: 2

Related Questions