我有問題獲取圖像和圖像鏈接顯示。我有一個應該顯示縮略圖的模型方法('thumbnail_'),它是鏈接全尺寸圖像的縮略圖。它不是渲染到網頁(image.html)。我究竟做錯了什麼?謝謝。Django - 顯示圖像和圖像鏈接
model.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
view.py
def image(request):
image = Image.objects.values('id', 'title', 'thumbnail_')
context = {
'image' : image,
}
return render_to_response('bsmain/image.html', context)
image.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>
我改變方法render_thumbnail,並使用Image.objects.all()。我也註釋掉了---- thumbnail_.allow_tags = True並從django.utils.safestring導入了mark_safe,然後改變了我的方法以反映「mark_safe」return mark_safe(「」「」「」%( (self.image。名稱,self.thumbnail.name))) – BillB1951 2012-01-30 00:44:38
我現在得到的標籤,看起來應該像他們應該工作,但他們不呈現縮略圖或鏈接。 – BillB1951 2012-01-30 00:57:06