简体   繁体   English

从邮递员发送带有图像/文件的嵌套 JSON 数据:Django REST 框架

[英]Send nested JSON data with image/file from postman: Django REST framework

I want to POST the following data:我想发布以下数据:

{
    "user": {
        "name": "user name",
        "email": "user@example.com",
        "phone_number": "01XXXXXXXXX",
        "user_type": "MGR"
    },
    "img": "image_data",
    "manager_brands": [
        2,
        1
    ]
}

How can I pass this JSON data through postman ?如何通过postman传递此 JSON 数据? Challenges I am facing:我面临的挑战:

  1. This is a nested JSON data这是一个嵌套的 JSON 数据
  2. I am passing an image with it.我正在传递一个图像。

Note: I wrote the nested serializers to GET/PUT/PATCH/DELETE requests.注意:我为 GET/PUT/PATCH/DELETE 请求编写了嵌套序列化程序。 Everything works fine when I don't send an image (image is optional here) .当我不发送图片时,一切正常(图片在这里是可选的)

Convert your Image to base64Image and send it through the JSON data.将您的 Image 转换为 base64Image 并通过 JSON 数据发送。

All you need to do is:您需要做的就是:

  1. go to https://www.base64-image.de/ and convert the image to base64 format.转到https://www.base64-image.de/并将图像转换为 base64 格式。 Copy the encoded result.复制编码结果。
  2. Install django-extra-fields package in your project from here这里在你的项目中安装 django-extra-fields 包
  3. In your serializer_class , change the image field like the following code:在您的serializer_class中,像以下代码一样更改图像字段:

serializers.py

...
from drf_extra_fields.fields import Base64ImageField
...
 
...
class ProfileSerializer(serializer.ModelSerializer):
    user = UserSerializer()
    img = Base64ImageField(required=False)

    class Meta:
        model = Profile
        fields = ('user', 'img', 'manager_brands')
...
  1. Now, go to your postman and send the JSON data like the following.现在,去你的postman那里发送 JSON 数据,如下所示。 Remember to send that encoded image in your img field in JSON.请记住以 JSON 格式在您的img字段中发送该编码图像。
{
    "user": {
        "name": "user name",
        "email": "user@example.com",
        "phone_number": "01XXXXXXXXX",
        "user_type": "MGR"
    },
    "img": "<base64 encoded image>",
    "manager_brands": [
        2,
        1
    ]
}

Hope this helps :D希望这会有所帮助:D

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM