在settings.py
MEDIA_ROOT = '/path/to/yourmediafolder/'
MEDIA_URL = '/media/' # whatever but it should same in `urls.py`
在urls.py
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT}))
然后在template
<img src="{{ MEDIA_URL }}images/imagename.jpg"/>
注意:这里image
应该是'/path/to/yourmediafolder/images/imagename.jpg'
完整示例:
我有一个test.jpg
图像'/home/me/test.jpg
MEDIA_ROOT = '/home/' # or /home/me/ but change url in image src
MEDIA_URL = '/media/'
#urls.py same as above
在template
<img src="{{ MEDIA_URL }}me/test.jpg"/> # or <img src="{{ MEDIA_URL }}test.jpg"/> as or condition above in MEDIA_ROOT.
请注意, {{ MEDIA_URL }}me
它们之间没有/
,因为MEDIA_URL='/media/
您可以通过以下方式进行测试:
http://domain.com/media/me/test.jpg # or http://domain.com/media/test.jpg as OR condition in MEDIA_ROOT
在当地:
http://localhost:8000/media/me/test.jpg #in locally