play <audio></audio> file in django te

2019-03-06 08:22发布

I've been struggling with this for so long that I'm bordering depression.

I have a model called "Song" that looks like this.

from django.db import models

class Song(models.Model):
    title = models.CharField(max_length=100)
    songfile = models.FileField()
    duration = models.FloatField()
    isPlaying = False

    def __str__(self):
        return self.title

When you upload an mp3 file from the index page, it creates an instance of this model and stores the file in myapp/songdir/ using this view:

def home(request):

    if request.method == 'POST':
        form = UploadForm(request.POST, request.FILES)
        if form.is_valid():
            song_title = request.POST.items()[1][1]
            song_address = 'upnplay/songdir/' + song_title + '.mp3'
            with open(song_address, 'wb+' ) as destination:
                for chunk in request.FILES['file'].chunks():
                    destination.write(chunk)
                audio = MP3(song_address)
                c = Song(title = song_title, songfile = song_address, duration = audio.info.length)
                c.save()
            return HttpResponseRedirect('')
    else:
        form = UploadForm()
    c = {'form': form}
    c.update(csrf(request))
    return render(request, 'index.html', {'form': form})

Then I have a template called "choosesong" that displays a list of songs that I get from the model instances saved:

{% extends 'index.html' %}


{% block content %}
<div class="row">
    {% for song in playlist %}
        <a href="playlist/{{song.title}}/"><h3>{{song.title}} -- {{song.duration}}</h3></a>
    {% endfor %}
</div>

{% endblock %}
{% block form %}{% endblock %}

When I click on one of this links, I want a new template to be rendered, with a element that plays the song whose name I clicked. The template that I render is this one:

{% extends 'index.html' %}

{% block content %}

<div class='row'>
    {{link}}
    <audio controls>
        <source src="../../{{ link }}" type="audio/mpeg">
        Your browser does not support the audio element.
    </audio>
</div>

{% endblock %}

And the view I use to deliver it is the following:

def playAudioFile(request, songtitle):
    name = urllib.unquote(songtitle)
    song = get_object_or_404(Song, title=name )
    return render(request, 'playlist.html', {'link': song.songfile })

For some reason I can't get it to play the song inside the audio element and I don't know what else to try.

Thank you beforehand.

1条回答
\"骚年 ilove
2楼-- · 2019-03-06 08:52

You should add MEDIA_ROOT and MEDIA_URL configuration. It will be easy to handle things. Here is the solution to your problem.

In settings.py:

MEDIA_ROOT=os.path.join(BASE_DIR,"songdir")
MEDIA_URL='/media/'

Also in settings.py add 'django.template.context_processors.media', in the TEMPLATES option's context_processors.

In project/urls.py:

from django.conf import settings
from django.conf.urls.static import static
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Then you can simply use:

{{link.url}} 

instead of hardcoding it in your template file.

查看更多
登录 后发表回答