Django ImageField.path 在 save 方法中返回 upload_to 的路径:
# models.py
class Message(models.Model):
image = models.ImageField(upload_to='mes-img', null=True, blank=True)
def image_tag(self):
if self.image:
# Printing "/base-dir/media/mes-img/image.png"
print(self.image.path)
# src=/media/mes-img/image.png
return mark_safe('<img src="{0}" width="100" />'.format(self.image.url))
def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
# Returns "/base-dir/media/image.png", should return "/base-dir/media/mes-img/image.png"
print(self.image.path)
# Returns "/media/image.png", should return "/media/mes-img/image.png"
print(self.image.url)
操作系统:Windows 10 64位
Python 3.6.4
Django 2.0.2
答案 0 :(得分:1)
upload_to
传递给Storage.save()
方法,请检查docs的这一部分。因此,只有在保存图像后才会将upload_to
添加到路径中。尝试这样的事情:
def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
super().save(force_insert, force_update, using, update_fields)
print(self.image.path)
print(self.image.url)
super().save()
会自动保存图片实例。