保存方法中没有 upload_to 的 Django ImageField.path returns 路径
Django ImageField.path returns path without upload_to within save method
Django ImageField.path returns 没有 upload_to 的路径 save 方法:
# 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)
OS: Windows 10 64 位
Python 3.6.4
Django 2.0.2
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()
会自动保存图片实例。
Django ImageField.path returns 没有 upload_to 的路径 save 方法:
# 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)
OS: Windows 10 64 位
Python 3.6.4
Django 2.0.2
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()
会自动保存图片实例。