python - django api如何上传多张图片
问题描述
我试了很多次,但我只注册了最后一个
我是我的模特
class PropertyImage(models.Model):
property = models.ForeignKey(Property, default=None, on_delete=models.CASCADE,)
images = models.ImageField(upload_to=upload, null=True, blank=True)
def __str__(self):
return str(self.images)
串行器
class PropertyImageSerializers (serializers.ModelSerializer):
class Meta:
model = PropertyImage
#fields =('name','')
fields = '__all__'
我的类视图处理程序发布请求,我尝试使用用户方法 FOR 循环所有图像并保存
看法
def post(self, request, *args, **kwargs):
property_id = request.data['property']
form_data = {}
for images in request.FILES.getlist('images'):
form_data['property']= property_id
form_data['images']=images
print(form_data)
serializer = PropertyImageSerializers(data=form_data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
for 不给我循环,不管我发送多少张图片
解决方案
我收到此错误消息: AttributeError: 'PropertyImageSerializers' object has no attribute 'property' 但我的模型你可以看到我有这个属性
property
不是PropertyImageSerializers
类的属性,这就是为什么AttributeError
我想你会在这里找到你的答案
更新:
你可以这样做
def post(self, request, *args, **kwargs):
property_id = request.data['property']
form_data = {}
form_data['property']= property_id
success = True
response = []
for images in request.FILES.getlist('images'):
form_data['images']=images
print(form_data)
serializer = PropertyImageSerializers(data=form_data)
if serializer.is_valid():
serializer.save()
response.append(serializer.data)
else:
success = False
if success:
return Response(response, status=status.HTTP_201_CREATED)
return Response(response,status=status.HTTP_400_BAD_REQUEST)
推荐阅读
- c# - 来自 URL 的 XML 未返回完整的 XML
- c# - 网络浏览器源为空
- javascript - 使用 vanilla JS 在本地服务器上使用 AJAX Javascript 请求触发 Python 脚本
- sql - 从 oracle sys_refcursor 函数返回整行
- facebook - Facebook Instant Game 中玩家关闭游戏后如何发送消息
- delphi - Delphi Android WIFI连接状态
- java - 在服务器端完成某些处理之前,如何保持或休眠一个 http 请求?
- java - 在 OkHttp 中信任/白名单证书(未找到证书路径的信任锚)
- html - 如果路径错误,请保持图像大小
- java - java.sql.SQLException:在调用 executeBatch() 期间语句已关闭