【问题标题】:Display img from an Id in Django在 Django 中显示来自 Id 的 img
【发布时间】:2021-07-02 14:45:02
【问题描述】:
在我的 Django work in progress 网站中,我有一个包含一千多个拇指的文件夹,其名称中有一个 Id,就像这样:
the_name_of_the_thumbnail_123456_low.png
此 ID 是从来自数据库的请求中检索的。为了在我的网站上显示相应的图片,我必须构建 url 字符串,可能是这样的:{% static images/low/the_name_of_the_thumbnail_ {{var}} _low %}。
如何执行此任务?使用正则表达式,来自模板?还是其他方式?
非常感谢
【问题讨论】:
标签:
python
django
regex
url
request
【解决方案1】:
最简洁的方法是将文件名存储在视图函数的变量中。像这样的:
"""
views.py
"""
def my_image_view(request):
image = models.Image.objects.first() # for example, you have a better way to get it from the DB :)
file_name = f"images/low/the_name_of_the_thumbnail_{image.id}_low.png"
context["file_name"] = file_name # or however else your context dict is called
return render("template", context=context)
<!-- my_image_template.html -->
<img src="{{ file_name }}" alt="..." />