无法在django中提供媒体文件

时间:2016-11-02 17:21:15

标签: python django

我正在尝试创建一个在线音乐播放器。我试图在django中播放一首歌。但它无法播放,因为它无法检测到音频文件。当我在互联网上阅读时,我已经在django中设置了媒体,但它没有工作。

以下是我的项目目录的屏幕截图:

enter image description here 检测和音乐是两个应用程序。我目前正在使用音乐应用程序。

Settings.py(包含在最后一个文件中)。

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>

1 个答案:

答案 0 :(得分:1)

MEDIA_URL传递给render,就像这样 render(request,'music/song.html',{'MEDIA_URL': settings.MEDIA_URL})并确保在from django.conf import settings中加入views.py

相关问题