来自 Django ImageField 的图像不会加载到模板中 [英] Images from ImageField in Django don't load in template

查看:33
本文介绍了来自 Django ImageField 的图像不会加载到模板中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在本地机器上使用 Django(1.5.1) 构建一个画廊.在我的相册模型中,我有一个 ImageField.有一个视图可以显示相册的所有图像.它运行良好,但最终图像不显示.如您所见,有图像边框,但无法加载图像.

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.

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 %}

如果这是我的相册地址:http://localhost:8000/gallery/1/

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

然后图片网址是:http://localhost:8000/media/images/albums/photo_4.JPG(浏览器输入404)

此媒体根目录和网址:

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

我的媒体根目录具有 777 权限.

My media root has 777 permission.

我现在该怎么办?问题出在哪里?

What should I do now? Where is the problem?

推荐答案

我知道问题出在哪里.MEDIA_URL 应该是这样的:

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/'

注意开头的斜杠字符.这是因为媒体是根服务器文件夹中的一个文件夹,与您调用的任何其他 url 无关.

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.

并将这些行添加到 urls.py 文件的末尾:

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)

您可以查看以下文档:https://docs.djangoproject.com/en/dev/操作方法/静态文件

希望能帮到你

这篇关于来自 Django ImageField 的图像不会加载到模板中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆