htmldjangobroken-image

media image rendered by django template broken


settings.py

INSTALLED_APPS = [...#'django.contrib.staticfiles',]

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

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

my_app/urls.py

urlpatterns = [
url(r'^welcome/', views.upload, name='upload'),] + 
static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

my_app/templates/template.html

<img src='media/my_image.jpeg'>

my_app/views.py

def upload(request):
    if request.METHOD == 'POST:
    ...
        return redirect(to another page)
    return render(request, 'template.html')

The template.html renders correctly, but the image is broken.

When I tried

curl -D - http://127.0.0.1:8000/my_app/welcome/media/my_image.jpeg

I get a 200 and when I go the welcome URL in the browser the backend returns

[22/Mar/2018 13:31:57] "GET /my_app/welcome/ HTTP/1.1" 200 411
[22/Mar/2018 13:31:57] "GET /my_app/welcome/media/my_image.jpeg HTTP/1.1" 200 411

so I don't think it's a url problem. Chrome is showing images. Any Ideas?


Solution

  • Firstly, your regex is missing a $, so it matches not only /welcome/ but also /welcome/media/my_image.jpeg (that's why your curl command returns status code 200). Change the URL pattern to:

    url(r'^welcome/$', views.upload, name='upload'), 
    

    Next, you are missing the leading slash to make it an absolute URL.

    <img src='/media/my_image.jpeg'>
    

    Finally, you need to server the media files as well as the static files. In development, you can add the following to your project's urls.py:

    urlpatterns = [
        ...
    ]
    
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)