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.