我是一名Django初学者,试图通过lightbird.net的教程来构建一个照片共享应用程序。我在开发服务器上显示照片时遇到问题。虽然我可以在管理界面上传和保存图像,但照片也不会显示在那里。相反,我看到了一个jpeg图标。当我在开发服务器上查看页面时,会出现相同的jpeg图标而不是照片。
昨天安装PIL和jpeg库需要一段时间,而我的应用程序现在运行时没有错误,我怀疑图像不显示的原因与这两个安装之一有关。我认为这可能是一个浏览器问题,但我无法查看来自Firefox,谷歌浏览器或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" alt=""
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 <<</a>
{% endif %}
<span class="current">
Page {{ albums.number }} of {{ albums.paginator.num_pages }}
</span>
{% if albums.has_next %}
<a href="?page={{ albums.next_page_number }}"> >> 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" alt="" src="/media%s" height="40" /></a>""" % (self.image.name, self.image.name)
thumbnail.allow_tags = True
答案 0 :(得分: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
答案 1 :(得分:1)
您可能还需要使用以下内容更新项目urls.py:
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT})