Prashant Kumar
Prashant Kumar

Reputation: 21

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

Upvotes: 0

Views: 458

Answers (3)

Prashant Kumar
Prashant Kumar

Reputation: 21

I got the answer from this thread Django MEDIA_URL and MEDIA_ROOT

What I did is added this line "django.core.context_processors.media" in settings.py inside Template Context_Processor.

Here

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'app/templates')]
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                 ...
                 'django.core.context_processors.media',
            ],
        },
    },
]

Upvotes: 1

flowfree
flowfree

Reputation: 16462

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.

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599450

You're not actually requesting those elements under MEDIA_URL, as you can see from the log file.

That's because you haven't actually passed those variables to the template, so they are being ignored.

Upvotes: 0

Related Questions