简体   繁体   English

Django DRF PUT 请求 ImageField

[英]Django DRF PUT Request ImageField

I am uploading images using the ImageField in Django.我正在使用 Django 中的 ImageField 上传图像。 After saving the image in the database when I GET the data to display on the frontend, I get it in the format:当我获取要在前端显示的数据时将图像保存在数据库中后,我以以下格式获取它:

{"pk":5,"employee_image":"/media/emp_temp_mast/5.png","first_name":"TEST",}

After changing the data on the frontend, I send a PUT request for the respective entry in the form:在前端更改数据后,我发送一个 PUT 请求以获取表单中的相应条目:

{"pk":5,"employee_image":"/media/emp_temp_mast/5.png","first_name":"DATA CHANGED",}

However I get the following error after making the request:但是,我在提出请求后收到以下错误:

employee_image: ["The submitted data was not a file. Check the encoding type on the form."]

How should I call the PUT request from frontend.我应该如何从前端调用 PUT 请求。

The suggestion by @Ross Rogers worked but I feel that it can get a little tedious as we expect every client side application to be aware that they have to Nuke the ImageField on every UPDATE request they intend to make. @Ross Rogers 的建议奏效了,但我觉得它可能会有点乏味,因为我们希望每个客户端应用程序都知道他们必须在他们打算提出的每个 UPDATE 请求上对 ImageField 进行 Nuke。 The client side should be able to make this abstraction and should not need to worry about the handling of the ImageField.客户端应该能够进行这种抽象,并且不需要担心 ImageField 的处理。

To achieve that I made the following change to the view where the backend receives the ImageField.为了实现这一点,我对后端接收 ImageField 的视图进行了以下更改。

class Emp_DetailView(APIView):

    def get_object(self, pk):
        try:
            return db_data
        except Emp_Mast.DoesNotExist:
            raise Http404

    def put(self, request, pk, format=None):
        db_data = self.get_object(pk)

        if(db_data["employee_image"] and db_data["employee_image"].startswith('http'))):
            img_name = dataDict["employee_image"].split("/")[-1]
            emp_img_temp = ContentFile(requests.get(dataDict["employee_image"]).content, name=img_name)
            dataDict["employee_image"] = emp_img_temp

        serializer = Emp_Mast_Serializer(db_data, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

A GET request is sent on the image URL and then the result is saved in a file format which can be used to send a PUT request在图像 URL 上发送 GET 请求,然后将结果保存为可用于发送 PUT 请求的文件格式

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

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