Prashant Kumar Prashant Kumar - 5 months ago 10
Python Question

Image and Sound (Media) not showing on django

I am trying to play an audio in django but it cannot find the audio file. I have setup the MEDIA_URL and MEDIA_ROOT but it still doesn't work. Please help me.
Below is the code snippet

settings.py

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


urls.py

urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$',home),
]

if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT


home.html

{% extends "layout/base.html" %}
{% block content %}
<h1> Sound Assessment Toolset </h1>
<audio src="{{MEDIA_URL}}master_sound/piano.mp3"></audio>
<img src="{{ MEDIA_URL }}images/batman.jpg"/>
{% endblock %}


Image of Project Directory

the log file :

Django version 1.8.7, using settings 'Sound_Assessment.settings'
Starting development server at http://127.0.0.1:8800/
Quit the server with CONTROL-C.
[17/Jun/2016 15:18:43] "GET / HTTP/1.1" 200 746
[17/Jun/2016 15:18:43] "GET /images/batman.jpg HTTP/1.1" 404 2321
[17/Jun/2016 15:18:43] "GET /master_sound/piano.mp3 HTTP/1.1" 404 2336
[17/Jun/2016 15:18:43] "GET /images/batman.jpg HTTP/1.1" 404 2321

Answer

You need to add media template context processor in your settings.py file:

TEMPLATES = [
    {
        ...
        'OPTIONS': {
            'context_processors': [
                ...
                'django.template.context_processors.media',
            ],
        },
    },
]

Then you will have {{ MEDIA_URL }} in your template.