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

查看:27
本文介绍了来自媒体文件的图像不会显示在 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

设置.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

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

推荐答案

Oh FFS....

显然是

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天全站免登陆