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
276 views
in Technique[技术] by (71.8m points)

images from media file wont get displayed in django template

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.

I'm using the sqlite3 server

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

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>

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

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Oh FFS....

aperently it's

MEDIA_URL = '/media/'

NOT

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

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

working img link looks like so:

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

you definitely need the:

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

in the url file also


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

...