Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
191 views
in Technique[技术] by (71.8m points)

python - Images from ImageField in Django don't load in template

I'm building a gallery using Django(1.5.1) on my local machine. In my Album model I have a ImageField. There is a view to show all images of an album. It works well, but at the end images don't show up. There's border of images as you can see but images don't load.

screenshot

enter image description here

models.py

class Category(models.Model):
 ###  
class Album(models.Model):   
    category = models.ForeignKey(Category, related_name='albums')
 ###
class Image(models.Model):
    album = models.ForeignKey(Album)
    image = models.ImageField(upload_to = 'images/albums/')

views.py

def detail(request, album_id):
    album = get_object_or_404(Album, pk=album_id)
    return render(request, 'gallery/detail.html', {'album': album})

detail.html

<h1>{{ album.title }}</h1>
{% for image in album.image_set.all %}
  <a>  <img src="{{ image.image.url }}" height="420"></a>
{% endfor %}

If this is my album address: http://localhost:8000/gallery/1/

Then image URL is:http://localhost:8000/media/images/albums/photo_4.JPG (I get 404 when enter it in browser)

This media root and url:

MEDIA_ROOT = '/media/'    
MEDIA_URL = '/localhost:8000/media/'  

My media root has 777 permission.

What should I do now? Where is the problem?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I have a clue on what's the problem. MEDIA_URL should be like this:

MEDIA_ROOT='<the full path to your media folder>' (i.e: '/home/ike/project/media/')
MEDIA_URL='/media/'

Note the slash character at the beginning. That is because media is a folder in your root server folder and not relative to whatever other url you call it.

And add these lines to the end of your urls.py file:

# You might need to import static function like this:
#from django.contrib.staticfiles.urls import static

urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

You can check the following documentation: https://docs.djangoproject.com/en/dev/howto/static-files

Hope this helps


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...