【问题标题】:File upload in Django restDjango rest中的文件上传
【发布时间】:2021-08-21 05:40:27
【问题描述】:

我创建了一个用于为现有用户上传“头像”的 api。

模型.py

  class ProfilePicture(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile_picture')
    profile_pic_path = models.FileField(
    upload_to=path_and_rename,
    max_length=254, blank=True, null=True
  ) class Meta:
    db_table = "profile_picture"

序列化器.py

class ProfilePictureSerializer(serializers.ModelSerializer):

  class Meta:
    model = ProfilePicture
    fields = '__all__'

Views.py

class ProfilePictureViewSet(viewsets.ModelViewSet):
  queryset = ProfilePicture.objects.all()
  serializer_class = ProfilePictureSerializer

  def create(self, request, *args, **kwargs):
    serializer = self.get_serializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
        custom_data = {
            "status": True,
            "message": 'Successfully uploaded your profile picture.',
            "data": serializer.data
        }
        return Response(custom_data, status=status.HTTP_201_CREATED)
    else:
        custom_data = {
            "status": False,
            "message": serializer.errors,
        }
        return Response(custom_data, status=status.HTTP_200_OK)

使用 'Django REST framework' UI 的 api 工作正常。

使用邮递员时出现此错误。

我该如何解决这个问题?

【问题讨论】:

    标签: django django-models django-rest-framework django-views django-rest-viewsets


    【解决方案1】:

    如果您有二进制(非字母数字)数据(或较大的有效负载)要传输,请尝试传递 content-type = multipart/form-data,否则,请使用 application /x-www-form-urlencoded。 参考:here

    【讨论】:

    • 在将 'multipart/form-data' 作为 'Content-Type' 传递时,我遇到了一个新错误 - ' "detail": "Multipart form parse error - Invalid boundary in multipart: None" ' .但是当我取消选中“内容类型”时它起作用了。取消选中该框可以吗?
    猜你喜欢
    • 1970-01-01
    • 2015-10-04
    • 2013-12-26
    • 2019-09-01
    • 2016-10-25
    • 1970-01-01
    • 2016-02-16
    • 2021-05-13
    • 2021-09-27
    相关资源
    最近更新 更多