问题描述
我在DRF中有一个视图-当我选择图像时,它可以正常工作,但是当没有选择文件时,它将引发错误:
The submitted data was not a file. Check the encoding type on the form.code invalid
我也尝试过有条件地将图像字段,即(mainimage和image_with_self)放入dat1 {}
中,但效果不佳。它在dat1={}
中不包含键值对,而是以old[Inmemoryuploaded:filename]
的形式放在字典对象之外
下面是我的代码
class ArtworkViewSet(viewsets.ModelViewSet):
queryset = Artwork.objects.all()
# import pdb; pdb.set_trace();
serializer_class = ArtworkSerializer
permission_classes = [AllowAny]
def partial_update(self,request,*args,**kwargs):
# import pdb; pdb.set_trace()
# kwargs['partial'] = True
partial = kwargs.pop('partial',True)
instance = self.get_object()
dat1={}
if request.data.get('own_work') == "false":
name_of_creator=request.data.get('name_of_creator')
name_of_owner=request.data.get('name_of_owner')
age_of_work=request.data.get('age_of_work')
house_no=request.data.get('house_no')
building_name=request.data.get('building_name')
else:
user_id=request.user.id
userprofile = UserProfile.objects.get(user=user_id)
name_of_creator=userprofile.name
name_of_owner=userprofile.name
house_no=userprofile.house_no
building_name=userprofile.building_name
# if(request.data['image_with_self']!= ""):
# dat1['image_with_self']=request.data['image_with_self']
# if(request.data['mainimage'] != ""):
# dat1['mainimage']=request.data['mainimage']
dat1={
'title': request.data.get("title"),'description': request.data.get("description"),'artcontest': request.data.get("artcontest"),'mainimage':request.data['mainimage'],'image_with_self':request.data['image_with_self'],'category_id': request.data.get("category"),'size': request.data.get("size"),'weight': request.data.get("weight"),'material': request.data.get("material"),'sale_lend': request.data.get("sale_lend"),'own_work': request.data.get("own_work"),'name_of_creator': name_of_creator,'name_of_owner': name_of_owner,'house_no': house_no,'building_name': building_name,}
# instance.save()
import pdb; pdb.set_trace()
serializer= self.get_serializer(instance,dat1,partial=partial)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data)
解决方法
您是否在序列化类中将image字段设为可选。如果不是,那么应该。
image = serializers.ImageField(required=False,max_length=None,allow_empty_file=True,use_url=True)
几天前,我遇到了类似的错误。可能it可以为您提供帮助。