首页 > 解决方案 > 如何使用模板中存储到 ImageField 的图像?

问题描述

我有以下models.py:

class Insurance(models.Model):
area = models.CharField(max_length=100)
title = models.CharField(max_length=50)
insurance_type = models.CharField(max_length=50)
area_photo = models.ImageField(upload_to='static/image')

这个模板:

                    {% for product in insurance.insuranceproducts_set.all %}
                    <li class="one_third btmspace-10 holder">
                    <figure><img src="{% static 'img/320x320.png' %}" alt="">
                        <div class="content">
                            <p><a href="{% url 'insurance:farmer_type' product.id %}">{{ product.title }}</a></p>
                        </div>
                    </figure>
                    </li>
                    {% endfor %}

问题是页面需要加载关于产品的简短描述。在这里它需要加载与该保险产品相关的图像。我怎样才能做到这一点?

标签: djangodjango-modelsdjango-templates

解决方案


文档中有一个很好的总结:https ://docs.djangoproject.com/en/2.1/faq/usage/#how-do-i-use-image-and-file-fields

尝试将您的图像标签更改为::

<img src="{{insurance.area_photo.url}}" alt="">

推荐阅读