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

查看:392
本文介绍了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



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



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/

然后图像URL是: http:// localhost:8000 / media / images / albums / photo_4.JPG(在浏览器中输入404时)

此媒体根和网址:

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

我的媒体根具有 777权限

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

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 file:

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/howto/static-files

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

希望这个帮助

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

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