Problem with serving pictures in Django

落爺英雄遲暮 提交于 2019-12-11 16:05:10

问题


I'm trying to create my first site in django and I've run into a problem. I'm trying to serve pictures,but it isn't working correctly. I have it set up in the following way:
In settings.py:

MEDIA_ROOT = 'C:/Users/John/Documents/My Dropbox/Infostuff/filmsite/media/'
MEDIA_URL = 'localhost:8000/static/'  
ADMIN_MEDIA_PREFIX = '/admin-media/'

In urls.py:

 (r'^static/(?P<path>.*)$', 'django.views.static.serve',
  {'document_root': settings.MEDIA_ROOT}),

It looks like this in the template page:

<img src="{{MEDIA_URL}}{{a.picture.url}}">

And it is parsed to this:

<img src="localhost:8000/static/portrets/0000138_Leonardo_D.jpg">

When I open the html page it doesn't display the pictures (I get the broken picture icon). If I however go to view the source and copy the above url and past it directly into my browser it does load the picture. What am I doing wrong?

I'm using Django 1.2. I'm not using Apache yet, because I would first like to get it working in a development environment.

PS: This is the first time I'm asking a question on this site, if I did something wrong, please tell.


回答1:


use:

MEDIA_URL = 'http://localhost:8000/static/' 

or

MEDIA_URL = '/static/' 



回答2:


Your MEDIA_URL should just be '/static/' - or, if you must, 'http://localhost:8000/static/'. Otherwise your browser is interpreting the localhost as part of the path, not the domain.




回答3:


Ok, I feel very stupid... I had to change

MEDIA_URL = 'localhost:8000/static/' 

to

MEDIA_URL = 'http://localhost:8000/static/' 

and then I had change

<img src="{{MEDIA_URL}}{{a.picture.url}}">

to

<img src="{{a.picture.url}}">

Thank you for your time.




回答4:


What version of Django are you using?

Can you post the generated HTML code? if the URL works when you copy and paste in the browser, it might be an html issue as well.

Have you looked at this page yet?

http://docs.djangoproject.com/en/dev/howto/static-files/

Update:

Can you post the model for a? is a.picture an image field? If so, then you don't need to put the MEDIA_URL in your img src, since it is already an absolute url and it should include the MEDIA_URL already. try removing that and see if it works.

<img src='{{a.picture.url}}' />

For more info see this page.

http://docs.djangoproject.com/en/1.3/ref/models/fields/#django.db.models.FileField.storage



来源:https://stackoverflow.com/questions/5532572/problem-with-serving-pictures-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!