Reputation: 219
I'm a Django beginner trying to work through this tutorial from lightbird.net to build a photo sharing app. I'm having a problem getting photos to display on the development server. While I can upload and save images on the admin interface, the photos also don't display there. Instead, a jpeg icon is all I see. When I view the page on the development server, the same jpeg icon appears rather than the photo.
It took me awhile to get PIL and jpeg library installed yesterday and while my app runs without errors now, I suspect the reason the images dont display has to do with one of those two installations. I thought it might be a browser issue, but i cant view the images from firefox, google chrome or safari.
Thanks in advance for the help. This site rocks!
The html for the code is :
{% 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 %}
The view is :
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})
And my models are:
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
Upvotes: 1
Views: 4421
Reputation: 145
You may also need to update your projects urls.py with the following:
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT})
Upvotes: 1
Reputation: 53326
You can use {{img.image.url}}
to get absolute url of your image field.
I hope you have referred
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
Upvotes: 1