【发布时间】:2015-09-28 20:08:25
【问题描述】:
如何在Django 1.8.4的django模板中显示上传的ProductPhoto图片?
适用于以下型号:
class Product(models.Model):
title = models.CharField(max_length=255, null=True, blank=True)
description = models.TextField(null=True, blank=True)
def __str__(self):
return self.title
def photos(self):
return ProductPhoto.objects.all()
class ProductPhoto(models.Model):
photo = models.ImageField(upload_to='img/product/', null=True, blank=True)
product = models.ForeignKey(Product, related_name='photos')
使用这些设置:
STATIC_ROOT = '/path/to/static/'
STATIC_URL = '/static/'
MEDIA_ROOT = '/path/to/media/'
MEDIA_URL = '/media/'
还有这些网址:
from django.conf.urls import include, url
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
urlpatterns = [
url(r'^$', 'myApp.views.index', name='index'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
如何在此模板中显示上传的ProductPhoto 对象:
{% for product in product_list %}
<div id="some-div">
{% for photo in product.photos.all %}
<div class="item"><img src="{{ MEDIA_URL }}{{ photo }}"/></div>
{% endfor %}
</div>
{% endfor %}
我以为我在正确的轨道上:{{ MEDIA_URL }}{{ photo }},但这是不正确的。我也尝试过{{ MEDIA_URL }}{{ photo.url }},但模板上都没有显示任何内容。有人能指出我正确的方向吗?
感谢您的想法。
【问题讨论】:
标签: python django static django-templates media