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

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

问题描述

我是Django的新手,我正在尝试通过一个简单的项目,我正在开发的名为都柏林人和一个名为书的应用程序来学习。目录结构如下:

 都柏林/书/ [包括models.py,views.py等] 
dubliners / templates / book /

我有一个JPG文件需要显示在标题中的每个网页。我应该在哪里存储文件?我应该使用哪个路径使标签显示它使用模板?我尝试过各种地点和路径,但目前还没有任何工作。



...



谢谢对于下面的答案。但是,我已经尝试了图像的相对路径和绝对路径,我仍然在网页中显示一个破碎的图像图标。例如,如果我的主目录中有图像,并在我的模板中使用此标签:

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

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

解决方案

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

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

然后,您只需确保该目录与相关文件一起存在。 / p>

在开发过程中是一个不同的问题。 django文档简洁清楚地解释了这一点,链接到这里并且在这里进行链接更有效,但基本上您将定义一个具有硬盘路径的网站媒体的视图。



此处


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/

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" /> 

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?

解决方案

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).

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.

Right here.

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

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