在django中检索imageField的url的最佳方法

时间:2015-01-29 09:47:50

标签: python django django-models

我正在使用以下型号:

class Product(models.Model):
    # some other stuff
    pictures = models.ManyToManyField(Image)

class Image(models.Model):
    # MEDIA_ROOT = /full/path/to/my/media/folder/
    image = models.ImageField(upload_to=settings.MEDIA_ROOT, default=DEFAULT_PROFILE_PICTURE)

然后在视图中我想检索图像,所以我运行以下代码:

for pic in product.pictures.all():
        pictures += [pic.image.url.replace(settings.PROJECT_ROOT, url)]

这里的问题是pic.image.url给了我系统路径,我期待相对路径(类似/media/mypicture.jpg)所以为了解决这个问题,我使用了replace函数,但在我看来它应该是一种更好的方式。

如何构建模型或访问图像以避免使用replace方法?

提前致谢

1 个答案:

答案 0 :(得分:3)

您不应该使用MEDIA_ROOT作为upload_to值。如果您想在没有任何子目录的情况下上传到MEDIA_ROOT,那么只需使用空字符串''

image = models.ImageField(upload_to='')
相关问题