返回链接的Django rest文件上载

2024-05-21 08:03:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我在stackoverflow中搜索工作fileupload APIView(使用最新版本的DRF)的示例,我已经尝试了许多不同的代码示例,但都没有成功(其中一些已弃用,一些-不是我想要的)

我有这些模型:

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)

除了rest解析器,我不想使用表单和其他任何东西 我想在将来得到POST'ed字段(例如name)

我相信解决办法很简单,但这行不通

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)

Tags: idtrue示例attachmentdocmodelsrequesttype
1条回答
网友
1楼 · 发布于 2024-05-21 08:03:14

删除parser_class将解决这里几乎所有的问题。请尝试以下代码段

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)


邮递员控制台截图
enter image description here

相关问题 更多 >