【发布时间】:2018-04-28 16:32:48
【问题描述】:
我有一个具有 ImageField 的模型 Employee,我返回模型的 REST API 响应,但它显示此错误
The 'face_image' attribute has no file associated with it.
我的 API 以这种方式生成响应: https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/api.py
@api_view(['GET'])
def get_employee(request):
data = [emp.as_dict() for emp in Employee.objects.all()]
return Response(data, status=status.HTTP_200_OK)
以下是型号:
https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/models.py
class Employee(models.Model):
...
face_image = models.ImageField(upload_to='face_image/', blank=True)
def face_image_url(self):
if self.face_image and hasattr(self.face_image, 'url'):
return self.face_image.url
def as_dict(self):
return {"id":self.id,
...
"face_image":self.face_image.url, <-- causes no file associated
...}
如何解决这个没有文件的 REST 响应处理图像字段?我尝试在Django The 'image' attribute has no file associated with it 中遵循一些方法,但我无法使用辅助函数来完成。
如果我删除图像字段,它将以这种方式生成响应https://imgur.com/a/JzQrD。但是我希望imagefield在结构中,在这种不存在文件的情况下如何处理
【问题讨论】:
-
没有序列化器,可以看这里是如何生成响应的gitlab.com/firdausmah/railercom/blob/master/railercomapp/api.py
-
没关系,我没有检查链接。顺便说一句,最好在答案中添加代码。我不认为直接将
dict表示传递给 django rest 框架是个好主意……使用序列化程序,您可以控制呈现数据的方式和内容(并避免出现错误)。 -
ok 将在几秒钟内完成,与此同时,如果没有图像字段 imgur.com/a/JzQrD,这就是响应的样子
标签: python django image rest url