Shivam Mitra Shivam Mitra - 1 month ago 6
Python Question

Not able to serve media files in django

I am trying to create an online music player. I was trying to play a song in django. But it was not able to play since it was not able to detect the audio file. I have set up the media in django as I read on the internet but it's not working.

Here is the screenshot of my project directory:

enter image description here
detect and music are two apps. I am currently working with music app.

Settings.py(included this at last of file).

STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static")
]
MEDIA_ROOT = os.path.join(BASE_DIR,"media")
MEDIA_URL = '/media/'


urls.py:

from django.conf.urls import *
from django.contrib import admin
from detect import views
from music import views
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^music/$',views.play,name = 'play')

]

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


views.py:

from django.shortcuts import render
from django.http import HttpResponse
def play(request):
return render(request,'music/song.html',{})


song.html:

<html>
<audio id="Player" autoplay>
<source src="{{MEDIA_URL}}/audio/test.mp3"/>
</audio>
</html>

Answer

Pass MEDIA_URL like to render like this render(request,'music/song.html',{'MEDIA_URL': settings.MEDIA_URL}) and make sure to include from django.conf import settings in your views.py.

Comments