简体   繁体   English

Django restframework 无法使用多部分解析器获取发布数据

[英]Django restframework can't get post data with a multipart parser

i am trying to save an object with an image using django restframework but when i use the FormParser and MultiPartParser classes the request.data object get seemingly encoded msgs and when i try to decode using utf-8 it outputs an error saying this data is not utf-8我正在尝试使用 django restframework 保存带有图像的 object,但是当我使用 FormParser 和 MultiPartParser 类时,request.data object 得到看似编码的消息,当我尝试使用 utf-8 解码时,它输出一个错误,说这个数据不是 8814968838106

i want to have access to the request.data data and be able to save the image for future requests我想访问 request.data 数据并能够为将来的请求保存图像

here is my view function:这是我的观点 function:

@parser_classes([FormParser, MultiPartParser])
@api_view(['GET', 'POST'])
@permission_classes([IsAuthenticated])
def products(request):
    if request.method == 'POST':
        print(request.data)

        serializer = ProductSerializer(data=request.data)
        
        serializer.initial_data['user'] = request.user.pk

        serializer.initial_data['price'] = float(
            request.data['price'])

        serializer.initial_data['quantity'] = int(
            request.data['quantity'])

        if serializer.is_valid():
            serializer.save()
            return Response({'message': "product added"}, status=status.HTTP_201_CREATED)
        else:
            print(serializer.errors)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

my front end code:我的前端代码:

export const addProduct = async (product) => {
    const fd = new FormData();
    fd.append("name", product.name);
    fd.append("price", product.price);
    fd.append("quantity", product.quantity);
    fd.append("image_url", product.image_url);

    console.log(product.image_url) //this prints a file object

    const response = await fetch(`${URL}/products`, {
        method: "POST",
        headers: {
            "Content-Type": `multipart/form-data; boundary=${fd._boundary}`,
        },
        body: fd,
    })
    return response
}

The image data is not being encoded as UTF-8 (Maybe, and if so), you can use the FileField or ImageField field in your serializer, along with the FormParser and MultiPartParser classes!图像数据未被编码为 UTF-8(可能,如果是的话),您可以在序列化程序中使用 FileField 或 ImageField 字段,以及 FormParser 和 MultiPartParser 类!

[UPDATED] Your view should be: [更新] 你的观点应该是:

@parser_classes([FormParser, MultiPartParser])
@api_view(['GET', 'POST'])
@permission_classes([IsAuthenticated])
def products(request):
    if request.method == 'POST':
        serializer = ProductSerializer(data=request.data)
        serializer.initial_data['user'] = request.user.pk

        if 'price' in request.data:
            serializer.initial_data['price'] = float(request.data['price'])
        else:
            return Response({'error': 'price not found in request data'}, status=status.HTTP_400_BAD_REQUEST)

        if 'quantity' in request.data:
            serializer.initial_data['quantity'] = int(request.data['quantity'])
        else:
            return Response({'error': 'quantity not found in request data'}, status=status.HTTP_400_BAD_REQUEST)

        if serializer.is_valid():
            serializer.save()
            return Response({'message': "product added"}, status=status.HTTP_201_CREATED)
        else:
            print(serializer.errors)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

And the serializer:和序列化器:

class ProductSerializer(serializers.ModelSerializer):
    image_url = serializers.ImageField()
    
    class Meta:
        model = Product
        fields = ['name', 'price', 'quantity', 'image_url', 'user']

so when i removed my headers it worked fine, so apparently if you choose to use multipart/form-data, the boundary must not appear in the file data that the server eventually receives.所以当我删除我的标题时它工作正常,所以显然如果你选择使用 multipart/form-data,边界不能出现在服务器最终接收的文件数据中。

The problem with multipart/form-data is that the boundary separator must not be present in the file data (see RFC 2388; section 5.2 also includes a rather lame excuse for not having a proper aggregate MIME type that avoids this problem). multipart/form-data 的问题是边界分隔符不能出现在文件数据中(参见 RFC 2388;第 5.2 节还包括一个相当蹩脚的借口,没有适当的聚合 MIME 类型来避免这个问题)。

so i fixed it by removing the boundary in the front end which makes my frontend code look something like this所以我通过删除前端的边界来修复它,这使得我的前端代码看起来像这样

const fd = new FormData();
fd.append("name", product.name);
fd.append("price", product.price);
fd.append("quantity", product.quantity);
fd.append("image_url", product.image_url);

console.log(product.image_url) // this print a File object

const response = await fetch(`${URL}/products`, {
    method: "POST",
    headers: {
        Authorization: `token ${localStorage.getItem("auth")}`
    },
    body: fd,
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法在 Django Restframework 中发布数据 - Not able to post the data in Django Restframework 覆盖Django RestFramework中的create方法以发布数据 - Overriding create method in Django RestFramework to POST data 无法使用 Axios 将来自 reactJs 的发布请求发送到 Django restframework - can't send post request from reactJs using Axios to Django restframework 在Django RestFramework中序列化数据 - Serialize data in django restframework Django RestFramework-POST上的可选嵌套序列化ID,GET上的详细信息? - Django RestFramework - Optional Nested serializer ID on POST, Detail on GET? Django restframework发送测试数据客户端的发布数据已损坏 - Django restframework send post data is broken from test APIClient 如何将 django restframework api 中的内容类型从 json 更改为多部分/表单数据或表单数据 - How to change content type in django restframework api from json to multipart/form-data or form data Django RestFramework POST 嵌套请求 - Django RestFramework POST nested request 有没有一种方法可以获取JSON数据而无需在Django restframework中建立模型? - Is there a way to get JSON data without tying to model in django restframework? 无法从Django获取POST数据(从React发送) - Can't get POST data from Django (sending it from React)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM