farhawa
farhawa

Reputation: 10398

Django - Why pictures are not served

Here is my project structure:

enter image description here

I need to upload a picture (via the admin interface ) before loading it in the template.

I found many posts about the same probleme and I followed the same steps described in answers:

My settings.py:

 DEBUG = True
 MEDIA_URL = '/media/'
 MEDIA_ROOT = os.path.join(BASE_DIR,'media')

My urls.py:

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

My models.py:

class Image_blog(models.Model):
    pic = models.ImageField(upload_to = 'blog')
    entry = models.ForeignKey(Entry,related_name='images')
    ...

Finally, in the template:

                    <div class="col-md-5">
                        <a href="blog-post.html">
                        {% for img in entry.images.all %}
                            <img class="img-responsive img-hover" src="{{ img.pic.url }}" alt="">
                        {% endfor %}
                        </a>
                    </div>

The problem that I got this error:

 GET http://localhost:8000/media/blog/django.png 404 (NOT FOUND)

Despite that the picture is there:

enter image description here

What I am doing wrong? Thanks in advance

Edit In case it can help:

Upvotes: 4

Views: 78

Answers (1)

Alasdair
Alasdair

Reputation: 308769

Make sure you have added this line to your root url config.

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

If you have, for example,

url(r'^blog/', include('blog.urls')),

and you add static() there, then Django would add a url pattern to serve the media files at /blog/^media/. That won't even make the files available at /blog/media/, because of the ^.

Upvotes: 4

Related Questions