Reputation: 8626
Friends,
I am using Django 1.6 and I have for the last week(!) been trying to display photos on a web page that are uploaded via the Django Admin site.
I know this is a common problem. I have tried reading the documentation, numerous SO questions like this one and this one all without success.
After uploading the image via the Admin site, I can see that the image exists in the following folder:
/home/ian/django/mysite/cars/media/images/1.JPG
However when the page loads (or trying to view the image after uploading them via the Admin Site) I see a 404 error. The source for the image shows the following:
<li><img src="/media/images/1.JPG" height="420"/></li>
The model.py has the following field:
photo = models.ImageField(upload_to='images/')
The urls.py has the following added:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
The template is:
{% extends "base.html" %}
<h1>Here</h1>
<p>{{ collectiondetail.title }}</p>
{% for photo in photos %}
<li><img src="{{ photo.photo.url }}" height="420"/></li>
{% endfor %}
{% endblock %}
Finally the settings.py are:
STATIC_ROOT = '/home/ian/django/mysite/cars/static/'
STATIC_URL = '/static/'
MEDIA_ROOT = '/home/ian/django/mysite/cars/media/'
MEDIA_URL = '/media/'
What have I missed?
Upvotes: 0
Views: 351
Reputation: 8626
Thanks to everyone for helping out. The default permissions when the files were uploaded were ok.
Finally managed to track down the problem to two settings.
MEDIA_URL was previously set to:
MEDIA_URL = '/media/'
Changed this to:
MEDIA_URL = '/cars/media/'
Changed the following in the urls.py file from
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
to
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.STATIC_ROOT,
}),
)
And now the images show as expected.
Upvotes: 0
Reputation: 11760
The urls.py snippet you are using is only for development and will only work in debug mode. Everything you have looks correct so double-check that in settings.py DEBUG = True
. From the docs on this feature:
This helper function works only in debug mode and only if the given prefix is local (e.g. /media/) and not a URL
Upvotes: 1