图像未在django模板中显示

时间:2018-02-20 14:46:26

标签: python django django-templates

我在Django模板中显示图像时遇到问题。除了imagefield之外,其他字段都正常显示。请在下面找到模板和模型。注意我的模型中没有声明任何图像字段。任何帮助都会很多赞赏。

Model.py

class Any(models.Model):
    Status=models.CharField(max_length=10,
                            choices=Status_choices,default='SUCCESS')
    Smoke=models.CharField(max_length=10,
                           choices=Smoke_choices,default='SUCCESS')
    Sanity=models.CharField(max_length=100,
                            choices=Sanity_choices,default='YES')

模板:

<table class = "table table-striped table-bordered">
    <thead>
            <tr>
              <th>Tag</th>
              <th>Smoke</th>
              <th>Status</th>
              <th>Sanity</th>                 
            </tr>
    </thead>         
{% for result in results %} 
   <tbody>
    <tr> 
        <td>
            {% if result.Status == SUCCESS %}<img src='/static/test/img/release.png' class="img-fluid rounded" alt="Generic placeholder thumbnail" width="20" height="20"/>                     
            {% elif result.Status == FAILURE %} <img src='/static/test/img/block.png' class="img-fluid rounded" alt="Generic placeholder thumbnail" width="20" height="20"/>
            {% elif result.Sanity == NO %}<img src='/static/test/img/thumbs-down.png' class="img-fluid rounded" alt="Generic placeholder thumbnail" width="20" height="20"/>
       {% endif %} </td> 
        <td>{{ result.Smoke }}</td>
        <td>{{ result.Status }}</td>
        <td>{{ result.Sanity }}</td>          
    </tr>
   </tbody>
{% endfor %}   

3 个答案:

答案 0 :(得分:3)

您需要使用下面的{% load static %} <img src="{% static 'test/img/release.png' %}" class="img-fluid rounded" alt="Generic placeholder thumbnail" width="20" height="20"/> 来获取静态图片。

dict

答案 1 :(得分:0)

使用此语法

src

答案 2 :(得分:0)

因为Python / Django应用程序不遵循目录结构来提供其视图,并且默认情况下Django不提供静态文件(例如css,javascript和图像),所以你要做的第一件事就是告诉Django在哪里可以找到您的静态文件夹。

通过在 settings.py 模块中设置STATICFILES_DIRS来完成。通常我们会使用BASE_DIR

执行此类操作

<强> settings.py

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static')
]

然后,考虑到您将STATIC_URL设置为/static/,您可以使用static模板代码正确呈现图片:

{% load static %}

<img src="{% static 'test/img/release.png' %}" class="img-fluid rounded" alt="Generic placeholder thumbnail" width="20" height="20"/>

基本上我们假设BASE_DIR manage.py 文件所在的目录。因此,您需要在其中创建名为 static 的文件夹,然后将文件夹 test / img 等放置。

  

PS:通常我们将{% load static %}放在模板的顶部,   在{% extends 'base.html' %}之后(如果你正在扩展这个   基础模板中的模板。)

使用Django处理静态资产并不是很明显,特别是如果你是来自PHP背景的话。

我在that answer about static files上详细阐述了一些内容,也许它可以用于更多地了解它是如何工作的。

相关问题