The image can upload to the file “upload” which located in mysite file, here is my code
setting.py
MEDIA_ROOT = 'C:/Python26/mysite/upload/media/'
MEDIA_URL = '/media/'
In the url.py
urlpatterns = patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT,}),
)
In the template
<img src="{{MEDIA_URL}}/{{pic}}" alt="Profile Picture" width="200"/>
However, the image still does not show in the website, but it indeed stored in the upload file. Someone could help me with that? Thanks
Given:
And the following template code:
The image
srccouldn’t possibly be/upload/Desert.jpg. The path should be starting with/media/. More likely than notMEDIA_URLis undefined and the value ofpicisupload/Desert.jpg. If that’s the case, then you’re probably missing the media template context processor. ChangeTEMPLATE_CONTEXT_PROCESSORSto:That will make
MEDIA_URLavailable in your template context. Then, you’ll also need to remove the slash after it, or you’ll end up with two (MEDIA_URLends with a slash), i.e.:Instead of:
Use:
UPDATE
If you’re still not getting a value for
MEDIA_URL, then you’re probably not usingRequestContext. You have to wrap your view’s context inRequestContextin order for the template context processors to do their thing.If you’re using
render_to_response, then:If you’re using Django 1.3+, you can just use the
rendermethod, which will do this for you automatically: