如何获取上传到 imagefield 的文件的文件名?
How to get filename of file uploaded to imagefield?
我需要在模板中传递在实例图像字段中上传的文件的文件名。
我的class:
def conference_directory_path(instance, filename):
return 'dialogues/conferences/conference_{0}/avatar/{1}'.format(instance.id, filename)
class Dialogue(models.Model):
...
avatar = models.ImageField(upload_to=conference_directory_path, blank=True)
...
模板:
<img src="/static/dialogues/conferences/conference_{{ dialogue.id }}/avatar/{{ dialogue.avatar.filename }}" alt="">
但是dialogue.avatar.filename渲染后是空字符串。怎么了?对话是对话模型的一个实例。
数据库中存储的实际上是文件名,而不是数据。此处描述了如何访问它:
https://docs.djangoproject.com/en/1.10/ref/models/fields/#filefield
All that will be stored in your database is a path to the file
(relative to MEDIA_ROOT). You’ll most likely want to use the
convenience url attribute provided by Django. For example, if your
ImageField is called mug_shot, you can get the absolute path to your
image in a template with {{ object.mug_shot.url }}.
所以我们有
<img src="{{ dialogue.avatar.url }}" alt="">
我需要在模板中传递在实例图像字段中上传的文件的文件名。
我的class:
def conference_directory_path(instance, filename):
return 'dialogues/conferences/conference_{0}/avatar/{1}'.format(instance.id, filename)
class Dialogue(models.Model):
...
avatar = models.ImageField(upload_to=conference_directory_path, blank=True)
...
模板:
<img src="/static/dialogues/conferences/conference_{{ dialogue.id }}/avatar/{{ dialogue.avatar.filename }}" alt="">
但是dialogue.avatar.filename渲染后是空字符串。怎么了?对话是对话模型的一个实例。
数据库中存储的实际上是文件名,而不是数据。此处描述了如何访问它:
https://docs.djangoproject.com/en/1.10/ref/models/fields/#filefield
All that will be stored in your database is a path to the file (relative to MEDIA_ROOT). You’ll most likely want to use the convenience url attribute provided by Django. For example, if your ImageField is called mug_shot, you can get the absolute path to your image in a template with {{ object.mug_shot.url }}.
所以我们有
<img src="{{ dialogue.avatar.url }}" alt="">