来自媒体文件的图像不会显示在django模板中 [英] images from media file wont get displayed in django template

查看:178
本文介绍了来自媒体文件的图像不会显示在django模板中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是django的新手,我一直在玩图片,然后显示它们。好吧,尝试来显示它们。

I'm new to django and I've been playing around with uploading pictures then displaying them. ... well trying to display them.

每当我尝试从模板中显示图片时,我只会得到破碎的图片链接图标。

Whenever I try to display the image from a template, I just get the broken image link icon.

我正在使用sqlite3服务器

I'm using the sqlite3 server

settings.py

settings.py

ROOT_DIR = os.path.dirname(os.path.dirname(__file__))
def location(f):
    return os.path.join(ROOT_DIR, f)
MEDIA_URL = 'http://127.0.0.1:8000/media/'
MEDIA_ROOT = location('media/')

models.py

models.py

class Image(models.Model):
    image = models.ImageField(upload_to = 'images/')

views.py

from imageupload.settings import MEDIA_ROOT, MEDIA_URL

def main(request):
    imgs = Image.objects.all()
    return render_to_response('index.html', {'images': imgs, 'media_root': MEDIA_ROOT, 'media_url': MEDIA_URL})

url.py

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

现在我刚刚使用管理员上传图片。这似乎工作正常,他们去我所期望的地方

Right now I've just used the admin to upload images. And that seems to work fine, they go to where I expect

但是当我尝试显示它们:

模板

But when I try to display them:
template

<!DOCTYPE html>
<html>
    <img src="<correct path to project>/media/images/photo_1.JPG" />

    {% for img in images %}
    <img src="{{ media_root }}{{ img.image.name }}" />
    <img src="{{ media_url }}{{ img.image.name }}" />
    <img src="{{ img.image.url }}" />
    {% endfor %}
</html>

我得到每个图标的破损。

浏览器源代码显示我:

I get the broken icon for each one.
The browser source code shows me:

<!DOCTYPE html>
<html>
    <img src="<correct path to project>/media/images/photo_1.JPG" />    
    <img src="<correct path to project>/media/images/photo_1.JPG" />    
    <img src="http://127.0.0.1:8000/media/images/photo_1.JPG" />
    <img src="http://127.0.0.1:8000/media/images/photo_1.JPG" />
</html>

这是有道理的,我只上传了一张照片。

,如果我复制一个硬链接并将其放入其他html文件中...它的作品

that makes sense, I only have one photo uploaded.
and if I copy one of the hard links and put it into some other html file ...it works

推荐答案

哦FFS ....

aperently它的

aperently it's

MEDIA_URL = '/media/'

MEDIA_URL = 'http://127.0.0.1:8000/media/' 

...尽管#'http://127.0.0.1:8000 / media /'正在其旁边书写

...despite #'http://127.0.0.1:8000/media/' being written right next to it

工作img链接如下所示:

working img link looks like so:

<img src="/media/images/photo_1.JPG" />

您绝对需要:

static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

url文件也

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

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