如何在 Django 模板中包含图像文件? [英] How do I include image files in Django templates?

查看:28
本文介绍了如何在 Django 模板中包含图像文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Django 的新手,我正在尝试通过我正在开发的一个名为dubliners"的简单项目和一个名为book"的应用程序来学习它.目录结构是这样的:

I'm new to Django and I'm trying to learn it through a simple project I'm developing called 'dubliners' and an app called 'book'. The directory structure is like this:

dubliners/book/  [includes models.py, views.py, etc.]
dubliners/templates/book/

我有一个 JPG 文件,需要在每个网页的页眉中显示.我应该在哪里存储文件?我应该为标签使用哪个路径以使用模板显示它?我已经尝试了各种位置和路径,但到目前为止没有任何效果.

I have a JPG file that needs to be displayed in the header of each Web page. Where should I store the file? Which path should I use for the tag to display it using a template? I've tried various locations and paths, but nothing is working so far.

...

感谢您在下面发布的答案.但是,我已经尝试了图像的相对路径和绝对路径,但仍然在网页中显示损坏的图像图标.例如,如果我的主目录中有一个图像并在我的模板中使用此标记:

Thanks for the answer posted below. However, I've tried both relative and absolute paths to the image, and I still get a broken image icon displayed in the Web page. For example, if I have an image in my home directory and use this tag in my template:

<img src="/home/tony/london.jpg" /> 

图像不显示.但是,如果我将网页另存为静态 HTML 文件,则会显示图像,因此路径是正确的.也许 Django 附带的默认 Web 服务器只会显示位于特定路径上的图像?

The image doesn't display. If I save the Web page as a static HTML file, however, the images display, so the path is correct. Maybe the default Web server that comes with Django will display images only if they're on a particular path?

推荐答案

在生产中,您只需从模板生成的 HTML 指向主机存储媒体文件的任何位置.所以你的模板将只有例如

In production, you'll just have the HTML generated from your template pointing to wherever the host has media files stored. So your template will just have for example

<img src="../media/foo.png">

然后您只需确保该目录与相关文件一起存在.

And then you'll just make sure that directory is there with the relevant file(s).

在开发过程中是一个不同的问题.django 文档对其进行了简洁明了的解释,链接到此处并在此处输入更有效,但基本上,您将为站点媒体定义一个视图,其中包含一个硬编码的磁盘位置路径.

during development is a different issue. The django docs explain it succinctly and clearly enough that it's more effective to link there and type it up here, but basically you'll define a view for site media with a hardcoded path to location on disk.

就在这里.

这篇关于如何在 Django 模板中包含图像文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆