【问题标题】:image is not showing in django template图像未显示在 django 模板中
【发布时间】:2017-07-12 09:02:24
【问题描述】:

我在 django 电子商务项目中显示图像文件时遇到问题。有人可以帮忙解决这个问题吗?

home.html

    {% for product in products %}
    <div class='col-sm-4'>
        <div class="thumbnail">
                {% if product.productimage_set.all %}
                        {% for item in product.productimage_set.all %}
                        <img class='img-responsive' src="{{ MEDIA_URL }}{{ item.image}}" />                         
                        {% endfor %}

                {% else %}
                <img class='img-responsive' src="{% static "img/placeholder.svg" %}" />
                {% endif %}

                <div class="caption">
                <a href='{{ product.get_absolute_url }}'> <h3>{{ product.title }}</h3></a>
                <p>{{ product.description|truncatewords:15}}</p>
                <p><a href="{{ product.get_absolute_url }}" class="btn btn-primary" role="button">View</a> <a href="#" class="btn btn-default" role="button">Button</a></p>
                </div>
         </div>
    </div> {% endfor %}

模型.py

class ProductImage(models.Model):
product = models.ForeignKey(Product)
image = models.ImageField(upload_to='products/images/')
featured = models.BooleanField(default=False)
thumbnail = models.BooleanField(default=False)
active = models.BooleanField(default=True)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)

def __unicode__(self):
    return self.product.title

settings.py

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR),"static","media")

【问题讨论】:

    标签: python django image templates


    【解决方案1】:
    <img class='img-responsive' src="{{ MEDIA_URL }}{{ item.image.url }}" />
    

    <img class='img-responsive' src="{{ item.image.url }}" />
    

    在主 urls.py 中

    from django.conf import settings 
    from django.conf.urls.static import static 
    
    
    urlpatterns = [
        # ... the rest of your URLconf goes here ...
    ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    

    【讨论】:

    • 根据您的建议修改后仍然没有显示图像。
    • 好的,你能显示通过检查元素发布的网址吗?
    猜你喜欢
    • 2021-12-10
    • 1970-01-01
    • 2019-11-25
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-16
    相关资源
    最近更新 更多