【发布时间】:2014-08-31 03:12:56
【问题描述】:
模型定义如下:
class Product(models.Model):
title = models.CharField(max_length=50)
summary = models.CharField(max_length=200)
def upload_path(self, filename):
return "product_images/" + self.title.lower().replace(" ", "_") + path.splitext(filename)[1]
img_sum = models.ImageField(upload_to=upload_path)
视图很简单:
class HomeView(generic.ListView):
context_object_name = 'products_list'
template_name = 'core/home.html'
model = Product
模板尝试显示图像:
{% for p in products_list %}
<a href="#">
<article class="product_frame">
<img src="{{ p.img_sum.url }}" />
<h3>{{ p.title }}</h3>
<p>{{ p.summary }}</p>
</article>
</a>
{% endfor %}
MEDIA_ROOT 明确设置为
MEDIA_ROOT = '/home/me/workspace/website/www/core/media/'
但是,MEDIA_ROOT 似乎从未附加到模型中定义的路径中。作为健全性检查,以下是我从 shell 中获得的通过 django 管理界面提供的测试 Product 实例:
In [20]: p = Product.objects.all()[3]
In [21]: p
Out[21]: <Product: Title : Test -- This is a test>
In [22]: p.img_sum
Out[22]: <ImageFieldFile: product_images/test.jpg>
In [23]: p.img_sum.url
Out[23]: '/media/product_images/test.jpg'
所以当我在位于www/core/templates 下的模板中调用{{ p.img_sum.url }} 时,它不会找到图像文件,因为相对url 应该是../media/product_images/test.jpg 而不是/media/product_images/test.jpg。
我怎样才能为我的图像文件解析好的 url?
【问题讨论】: