Django - Why Photos Don't Come

Here is my project structure:

enter image description here

I need to upload an image (via the admin interface) before uploading it to a template.

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

My .py settings:

 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 .py models:

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 is that I got this error:

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

Despite the fact that the image is:

enter image description here

What am I doing wrong? thanks in advance

Edit If this can help:

  • I am using django 1.8
+4
source share
1 answer

Make sure you add this line to the root url configuration .

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

If you have, for example,

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

static() , Django url /blog/^media/. /blog/media/ - ^.

+4

Source: https://habr.com/ru/post/1627683/


All Articles