如何在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 }}
,但都没有在模板上显示任何内容。有人能指出我正确的方向吗?
感谢您的想法。
答案 0 :(得分:0)
首先,删除照片模型上的photos()方法,因为它可能会被ProductPhoto对象上的related_name误解。
然后,只需执行以下操作:
{% for product in product_list %}
<div id="some-div">
{% for product_photo in product.photos.all %}
<div class="item"><img src="{{ product_photo.photo.url }}"/></div>
{% endfor %}
</div>
{% endfor %}
希望它有所帮助,
答案 1 :(得分:0)
以下是您需要更改的内容:
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
# this is wrong, get rid of it:
#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')
你不需要MEDIA_URL,django dev服务器知道如何处理它,(在生产中你需要配置apache,nginx等来为它们服务):
urlpatterns = [
url(r'^$', 'myApp.views.index', name='index'),
] # + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
就像这样:
{% for product in product_list %}
<div id="some-div">
{% for product_photo in product.photos.all %}
<div class="item"><img src="{{ product_photo.photo.url }}"/></div>
{% endfor %}
</div>
{% endfor %}