显示ImageField中的图像

时间:2017-06-03 14:42:33

标签: django python-3.x django-models

我尝试在我的网站的两个部分显示相同的硬币图像(文章列表和硬币库)。唯一的区别(我猜)是从文章页面我用外键调用它,而我从画廊直接调用它。

图片 显示在文章列表中,但不是在图库中。

以下是一些代码:

模特:

# coinCollection/models.py:
class coin(models.Model):
    #...
    coin_thumbnail = models.ImageField(max_length=500, upload_to = join(MEDIA_IMAGES_DIR, MEDIA_COINS_DIR), verbose_name='Miniature')
    #...

# blog/models.py:
class article(models.Model):
    #...
    article_money = models.ForeignKey(coin,
        null = True,
        on_delete = models.SET_NULL,
        related_name="money"
    )

意见:

# coinCollection/views.py:
class coinGallery(ListView):
    model = coin
    template_name = 'coinsCollection/gallery.html'
    context_object_name = 'coins_list'

    def get_queryset(self):
        coin_list = coin.objects.values('id', 'coin_name', 'coin_millesime', 'coin_thumbnail').order_by('coin_name')

        paginator = Paginator(coin_list, 3) # Show n coins per page

        page = self.request.GET.get('page')
        try:
            coins = paginator.page(page)
        except PageNotAnInteger:
            coins = paginator.page(1)
        except EmptyPage:
            coins = paginator.page(paginator.num_pages)
        return coins

# blog/views.py
class IndexView(generic.ListView):
    template_name = 'blog/articles.html'
    context_object_name = 'article_list'

    def get_queryset(self):
        article_list = article.objects.order_by('-article_pub_date')
        paginator = Paginator(article_list, 3) # Show n articles per page

        page = self.request.GET.get('page')
        try:
            articles = paginator.page(page)
        except PageNotAnInteger:
            # If page is not an integer, deliver first page.
            articles = paginator.page(1)
        except EmptyPage:
            # If page is out of range, deliver last page of results.
            articles = paginator.page(paginator.num_pages)
        return articles

并在模板中:

# gallery.html (Not displayed, empty var)
<img class="img-responsive" src="{{ coin.coin_thumbnail.url }}" alt="{{ coin.coin_name }}">

# articles.html (Displayed correctly)
<img class="img-responsive" src="{{ article.article_money.coin_thumbnail.url }}">

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

coinGallery视图中,您已将查询集转换为values()。这会将ImageFieldFile对象'coin_thumbnail'转换为其字符串表示形式,即'myimage.jpg',并且您无法使用Django的便捷属性.url。要使用.url属性,只需使用coin.objects.order_by()代替coin.objects.values().order_by()。或者,如果您更喜欢值,那么您需要将MEDIA_URL加入coin_thumbnail文件名以获取完整的文件路径。

答案 1 :(得分:1)

values仅返回相关路径。只需在模板上使用{{MEDIA_URL}}{{coin.coin_thumbnail}}即可。 (注意settings.py中定义的附加斜线)