Django DRF无法发送带有Image字段的PUT请求



我在React中有一个表单,我通过它发送一些数据,其中包括一个ImageField。我能够执行POST请求,并且数据被成功地发送到Django后端。然而,当我试图修改数据时,我得到employee_image:`

[quot;提交的数据不是文件。请检查形式。"]

这是GET请求中出现的数据:

[{"id":2."product_name":"XYZ";,"product_description":"XYZ";,"product_price":"12.00";,"product_unit_weight":"120.00〃;,"product_unit_weight_units":"GM";,"product_type":"CPG";,"product_image":"http://192.168.29.135:8000/media/product_images/xyz.png"},

这是我的models.py文件:

class ProductViewSet(viewsets.ModelViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializer
def post(self, request, *args, **kwargs):
product_name = request.data['product_name']
product_description = request.data['product_description']
product_price = request.data['product_price']
product_unit_weight = request.data['product_unit_weight']
product_unit_weight_units = request.data['product_unit_weight_units']
product_type = request.data['product_type']
product_image = request.data['product_image']
Product.objects.create(product_name=product_name, product_description=product_description, product_price=product_price, product_unit_weight=product_unit_weight, product_unit_weight_units=product_unit_weight_units, product_type=product_type, product_image=product_image)
return Response({'message':'Product created successfully'}, status=200)
def update(self, request, *args, **kwargs):
print('Put method running')
pk = self.kwargs.get('pk')
product = get_object_or_404(Product.objects.all(), pk=pk)
print(product)
if (product.product_image.startswith('http')):
img_name = dataDict["product_image"].split("/")[-1]
product_img_temp = ContentFile(request.get(dataDict["product_image"]).content, name=img_name)
dataDict['product_img'] = product_img_temp
serializer = ProductSerializer(product, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

我试着遵循这个响应,并用update((编辑了我的models.py,如上所示。但我得到的错误是:

"产品"对象没有属性"数据">

此外,当我在update((方法中打印产品时,我只打印产品名称,而不打印其余字段。我不明白为什么我会遇到这个问题。任何帮助都将不胜感激。提前谢谢。

`

以下是您必须克服的几个问题。

  1. 从客户端(React(,您需要制作FormData来发送图像或文件
  2. 在python中,每个对象都有一些特殊的魔术方法,其中一个是arstr,该方法返回字符串。当我们打印一个对象时,除了打印完整的对象数据外,还打印了这个str方法字符串。如果要打印完整数据,则需要使用print(product.__dict__)

您可以使用;补丁";方法来提出您的请求,而不是";放入";要求Patch使用了partial_update((函数,因此,您还需要定义一个partial_uUpdate((函数。

最新更新