【问题标题】:Django image attribute has no file associated with it REST APIDjango 图像属性没有与之关联的文件 REST API
【发布时间】: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


【解决方案1】:

这里:

"face_image":self.face_image.url, &lt;-- causes no file associated

您实际上并没有使用您的 face_image_url 方法。

应该是:

`"face_image":self.face_image_url()

正如我上面所说,我认为像您那样处理模型的序列化确实是个坏主意。我强烈建议你看看serializers

【讨论】:

  • @Clément,这是我听说的新事物。您能否为此提供一个文档链接。我试过了,但它不适合我。
【解决方案2】:

您需要明确处理这种情况。在这种情况下,您的 as_dict 方法应如下所示:

def as_dict(self):
    return {"id":self.id,
            ...
            "face_image": self.face_image.url if self.face_image else None
            ...}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-19
    • 1970-01-01
    • 2016-02-06
    • 2022-12-11
    • 2015-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多