如何使用Django将每个图像嵌入HTML页面目录中?

2024-04-25 15:11:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试为Django项目中位于static的目录中的每个文件创建图像标记。最好的方法是什么?我想我可以用os.listdir编写纯python,只需使用字符串使用文件名将图像标记连接在一起,但我确信有更好的方法使用Django的HTML格式。我还没弄明白

示例:文件夹中有img1.jpgimg2.jpg

我如何制作:

<img src="img1.jpg" alt="img1.jpg" height="100px" width="100px">
<br>
<img src="img2.jpg" alt="img2.jpg" height="100px" width="100px">
<br>

Tags: 项目django方法标记图像brsrcimg
1条回答
网友
1楼 · 发布于 2024-04-25 15:11:38

我不清楚你在找什么,但是

create image tags for every file in a directory located in static

我假设您希望使用{% static %}标记加载图像:

{% load static %}
...
<img src="{% static 'path_to_image' %}" alt="img1.jpg" height="100px" width="100px">
<!  Watch out the single and double quotes  >

请记住在settings.py中包含以下内容:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'), // or wherever you put your static files
]

我认为它现在是自动的,但请检查您的INSTALLED_APPS

INSTALLED_APPS = [
    ...
    'django.contrib.staticfiles',
]

与像C:/foo/baz/bar/这样的硬编码路径相比,加载静态标记更好,因为它总是在不同的平台上工作,因为每个操作系统都有自己的处理文件的方法,我希望这能回答您的问题

相关问题 更多 >

    热门问题