图像未显示在 Django 应用程序上

Posted

技术标签:

【中文标题】图像未显示在 Django 应用程序上【英文标题】:Images not showing on Django App 【发布时间】:2012-07-19 04:58:32 【问题描述】:

我是一名 Django 初学者,正在尝试通过 lightbird.net 上的本教程来构建照片共享应用程序。我在让照片显示在开发服务器上时遇到问题。虽然我可以在管理界面上上传和保存图像,但照片也不会显示在那里。相反,我只看到一个 jpeg 图标。当我在开发服务器上查看页面时,会出现相同的 jpeg 图标而不是照片。

昨天我花了一段时间才安装 PIL 和 jpeg 库,虽然我的应用程序现在运行没有错误,但我怀疑图像不显示的原因与这两个安装之一有关。我认为这可能是浏览器问题,但我无法查看来自 firefox、google chrome 或 safari 的图像。

提前感谢您的帮助。这个网站太棒了!

代码的html是:

% extends "pbase.html" %

% block content %
    <div class="main">
        <!-- Albums -->
        <ul>
            % for album in albums.object_list %
                <div class="title"> album.title  ( album.image_set.count images)</div>
                <ul>
                    % for img in album.images %
                        <a href=" media_url  img.image.name "><img border="0"  
                            src=" media_url  img.thumbnail2.name " /></a>
                    % endfor %
                </ul>
            % endfor %
        </ul>

        <!--Next/Prev page links-->
        % if albums.object_list and albums.paginator.num_pages > 1 %
        <div class="pagination">
            <span class="step-links">
                % if albums.has_previous %
                    <a href= "?page= albums.previous_page_number ">previous &lt;&lt;</a>
                % endif %

                <span class="current"> 
                    &nbsp;Page  albums.number  of  albums.paginator.num_pages 
                </span>
                % if albums.has_next %
                    <a href="?page= albums.next_page_number "> &gt;&gt; next</a>
                % endif %
            </span>
        </div>
        % endif %
    </div>
% endblock %

观点是:

def main(request):
    albums = Album.objects.all()
    if not request.user.is_authenticated():
        albums = albums.filter(public=True)

    paginator = Paginator(albums, 10)
    try: page = int(request.GET.get("page", "1"))
    except ValueError: page = 1

    try:
        albums = paginator.page(page)
    except(InvalidPage, EmptyPage):
        albums = paginator.page(paginator.num_pages)

    for album in albums.object_list:
        album.images = album.image_set.all()[:4]

    return render_to_response("list.html", 'albums':albums, 'user':request.user, 'media_url':MEDIA_URL) 

我的模型是:

class Album(models.Model):
    title = models.CharField(max_length=60)
    public = models.BooleanField(default=False)
    def __unicode__(self):
        return self.title

    def images(self):
        lst = [x.image.name for x in self.image_set.all()]
        lst = ["<a href='/media/%s'>%s</a>" % (x, x.split("/")[-1])for x in lst]
        return join(lst, ",")
    images.allow_tags = True


class Tag(models.Model):
    tag = models.CharField(max_length=60)
    def __unicode__(self):
        return self.tag


class Image(models.Model):
    title = models.CharField(max_length=60, blank=True)
    image = models.FileField(upload_to="images/")
    tags = models.ManyToManyField(Tag, blank=True) 
    albums = models.ManyToManyField(Album, blank=True)
    created = models.DateTimeField(auto_now_add=True)
    rating = models.IntegerField(default=50)
    width = models.IntegerField(blank=True, null=True)
    height = models.IntegerField(blank=True, null=True)
    user = models.ForeignKey(User, null=True, blank=True)

    thumbnail2 = models.ImageField(upload_to="images/", blank=True, null=True)

    def save(self, *args, **kwargs):
        """save image dimensions."""
        super(Image, self).save(*args, **kwargs)
        im = PImage.open(os.path.join(MEDIA_ROOT, self.image.name))
        self.width, self.height = im.size

        # large thumb
        fn, ext = os.path.splitext(self.image.name)
        im.thumbnail((128,128), PImage.ANTIALIAS)
        thumb_fn = fn + "-thumb2" + ext
        tf2 = NamedTemporaryFile()
        im.save(tf2.name, "JPEG")
        self.thumbnail2.save(thumb_fn, File(open(tf2.name)), save=False)
        tf2.close()

        #small thumb
        im.thumbnail((40,40), PImage.ANTIALIAS)
        thumb_fn = fn + "-thumb" + ext
        tf = NamedTemporaryFile()
        im.save(tf.name, "JPEG")
        self.thumbnail2.save(thumb_fn, File(open(tf.name)), save=False)
        tf.close()

        super(Image, self).save(*args, **kwargs)    

    def size(self):
        return "%s x %s" % (self.width, self.height)

    def tags_(self):
        lst = [x[1] for x in self.tags.values_list()]
        return str(join(lst, ', '))

    def __unicode__(self):
        return self.image.name

    def albums_(self):
        lst = [x[1] for x in self.albums.values_list()]
        return str(join(lst, ', '))

    def thumbnail(self):
        return """<a href="/media/%s"><img border="0"  src="/media%s"  /></a>""" % (self.image.name, self.image.name)
    thumbnail.allow_tags = True

【问题讨论】:

【参考方案1】:

您可以使用img.image.url 获取图片字段的绝对网址。 我希望你已经提到 https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.FileField.storage

How do I include image files in Django templates?

How to show an image in template uploaded from admin panel Django 1.3

【讨论】:

【参考方案2】:

您可能还需要使用以下内容更新您的项目 urls.py:

(r'^media/(?P<path>.*)$', 'django.views.static.serve', 
'document_root': settings.MEDIA_ROOT)

【讨论】:

以上是关于图像未显示在 Django 应用程序上的主要内容,如果未能解决你的问题,请参考以下文章

Django staticfiles图像未显示

使用 Wea​​syprint 的 PDF 输出不显示图像(Django)

Django图像未显示

Django 应用程序未在管理页面中显示注册模型

Django3.0:来自数据库的图像在 debug=False 后未显示

颤振推送通知图像未在所有设备上显示