【问题标题】:MEDIA_ROOT not appended to the ImageField urlMEDIA_ROOT 未附加到 ImageField url
【发布时间】: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?

【问题讨论】:

    标签: python django


    【解决方案1】:

    尝试将settings.py中的MEDIA_URL定义为'../media/'

    【讨论】:

    • 在这种特定情况下它的价值应该是什么?我尝试了“/media/”,但没有成功。
    • 谢谢。现在似乎不是相对路径的问题。在我的模板中,我手动添加了这个:&lt;img src="/media/product_images/test.jpg" /&gt; &lt;img src="/static/core/img/envelope.png" /&gt; 第一个图像不会显示,但第二个图像会显示,尽管两个文件都肯定存在。我真的不明白。
    • 所以要明确一点:路径应该相对于views.py 的位置,在这种情况下,'/media/' 对于 MEDIA_URL 是正确的(实际上我什至不需要它)。问题只是图像存储在 /media 下时不会显示,如果它们存储在 /static 下则会显示。
    • 当 debug = True 时,静态(媒体)服务的行为略有不同。 Try out those docs.
    【解决方案2】:

    所以问题与文件位置无关,而是与 Django 在开发环境中默认不提供媒体文件这一事实有关。 This question 帮助解决了这个问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-24
      • 2023-03-06
      • 2021-01-12
      • 1970-01-01
      • 1970-01-01
      • 2017-10-29
      • 1970-01-01
      • 2019-09-09
      相关资源
      最近更新 更多