Django DRF PUT请求ImageField [英] Django DRF PUT Request ImageField
问题描述
我正在使用Django中的ImageField上传图像。当我获取要显示在前端的数据时,将图像保存在数据库中之后,我以以下格式获取图像:
I am uploading images using the ImageField in Django. 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",}
更改前端的数据后,我以以下形式发送对相应条目的PUT请求:
After changing the data on the frontend, I send a PUT request for the respective entry in the form:
{"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."]
我应该如何从前端调用PUT请求。
How should I call the PUT request from frontend.
推荐答案
@Ross Rogers的建议奏效了,但我觉得它会有些乏味,因为我们希望每个客户端应用程序都知道它们必须在他们打算发出的每个UPDATE请求上对ImageField进行核对。客户端应该能够进行这种抽象,并且不必担心ImageField的处理。
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. 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.
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)
在图像URL上发送了GET请求,然后将结果保存为文件格式可以用来发送PUT请求
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
这篇关于Django DRF PUT请求ImageField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!