Django显示图像和图像链接

2024-05-13 09:41:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有问题得到图像和图像链接显示。我有一个模型方法('thumbnail_u'),它应该显示一个缩略图,它是链接整个尺寸图像的链接。它不会呈现到网页(图像.html). 我做错什么了?谢谢您。在

在模型.py在

class Image(models.Model):
    title = models.CharField(max_length=60, blank=True, null=True)
    image = models.ImageField(upload_to="images/", blank=True, null=True)
    thumbnail = models.ImageField(upload_to="images/", blank=True, null=True)
    thumbnail2 = models.ImageField(upload_to="images/", blank=True, null=True)
    #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)
    listings = models.ForeignKey(Listings)

def save(self, *args, **kwargs):
    # Save image dimensions
    super(Image, self).save(*args, **kwargs)
    im = PImage.open(pjoin(MEDIA_ROOT, self.image.name))
    self.width, self.height = im.size

    # large thumbnail
    fn, ext = os.path.splitext(self.image.name)
    im.thumbnail((256,256), 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 thumbnail
    im.thumbnail((60,60), PImage.ANTIALIAS)
    thumb_fn = fn + "-thumb" + ext
    tf = NamedTemporaryFile()
    im.save(tf.name, "JPEG")
    self.thumbnail.save(thumb_fn, File(open(tf.name)), save=False)
    tf.close()

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


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

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

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

在视图.py在

^{pr2}$

在图像.html在

<TABLE id="some_id">    
<TBODY>
    {% load humanize %}
    {% for row in image %}
    <tr>
        <td>{{ row.id }}</td>
        <td>{{ row.title}}</td>
        <td>{{ row.thumbnail_}}</td>            
    </tr>
    {% endfor %}
</TBODY>

Tags: name图像imageselftruemodelssavenull
2条回答

我很惊讶你能得到任何东西。你的观点是:

image = Image.objects.values('id', 'title', 'thumbnail_')

不允许,因为thumbnail_不是字段,它是Image类上的方法。values只对字段进行操作,返回包含这些名称的dict的queryset。即使在values调用中使用了实际字段thumbnail,模板仍然无法正确输出,因为values返回的dict中不存在{}方法。在

简单的解决方案是在这里使用一个标准的Image.objects.all()调用-试图限制返回的字段数是过度优化的。在

(另外,请尝试为您的方法取一个更好的名称:类似render_thumbnail的名称比仅仅thumbnail_更好。)

我看不到任何名为thumbnail_的属性:

image = Image.objects.values('id', 'title', 'thumbnail_')

以及

^{pr2}$

检查图像是否在正确的目录中。在

相关问题 更多 >