所以我在Django应用程序上播放mp3文件时遇到了麻烦。
settings.py - 添加了MEDIA_ROOT和MEDIA_URLS
MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads')
MEDIA_URL = '/uploads/'
models.py - 我有一个简单的音频类设置
class Audio(models.Model):
author = models.ForeignKey('auth.User')
title = models.CharField(max_length=200)
audio_file = models.FileField(upload_to='audio/', blank=True)
description = models.TextField()
featured_image = models.URLField(max_length=500)
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
views.py - 这是我的观点
class AudioListView(ListView):
context_object_name = 'audio'
template_name = 'media/audio/audio_list.html'
model = Audio
audio_list.html - 这是我的模板
{% block content %}
{% for aud in audio %}
<p>Audio Title: {{ aud.title }}</p>
<img src="{{ aud.featured_image}}" alt="">
<hr>
<audio controls>
<source src="{{ aud.audio_file }}" type="audio/mp3">
</audio>
<hr>
<p>Audio Description: {{ aud.description }}</p>
{% endfor %}
{% endblock %}
我可以进入并添加音频文件,然后将其上传到以下目录
# myapp -> uploads -> audio -> audio.mp3
通过以下设置,html5音频播放器甚至不显示。当我检查页面的来源时,我得到以下内容:
<audio controls>
<source src="audio/audio.mp3" type="audio/mp3">
</audio>
我已经梳理了Django文档。我搜遍了谷歌。我不认为拉文件路径并播放它会很困难。
任何建议都将不胜感激!
编辑:添加我的网址文件
# mainapp/urls.py
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.flatpages import views
from home.views import HomeTemplateView
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'', include('home.urls')),
url(r'^blog/', include('blog.urls')),
url(r'^media/', include('media.urls')),
url(r'^about/', views.flatpage, {'url': '/about/'}, name='about'),
url(r'^contact/', views.flatpage, {'url': '/contact/'}, name='contact'),
url(r'^donations/', views.flatpage, {'url': '/donations/'},
name='donations'),]
# media/urls.py
from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import include, url
from media.views import AudioListView, VideoListView
urlpatterns = [
url(r'^video/$', VideoListView.as_view(), name='video'),
url(r'^audio/$', AudioListView.as_view(), name='audio'),
]
答案 0 :(得分:0)
首先:您需要获取所有音频文件
class AudioListView(ListView):
template_name = 'media/audio/audio_list.html'
model = Audio
def get_context_data(self, **kwargs):
context = super(AudioListView, self).get_context_data(**kwargs)
context['audio'] = Audio.objects.all()
return context
然后你需要网址:
<source src="{{ aud.audio_file.url }}" type="audio/mp3">
更改目录的权限以查看页面上的播放器。
chmod a+r -R uploads