0

Recently I've had some trouble with serving .mp3 files in templates via audio tag and providing a download. I solved it though I guess the solution is poor. That's why I ask here. I'm using Django 1.4 Python 2.7.

Here is the way I did it (I've chosen to serve them like static files and provide download in another view because the first will open a new tab and play the file):

models.py

class Audio(models.Model):
id_audio = models.IntegerField(primary_key=True)
date_created = models.DateTimeField()
file_link = models.CharField(max_length=45, unique=True)
class Meta:
    db_table = u'audio'

views.py

from django.views.static import serve
def customize_media_serving(request, path, document_root=None, show_indexes=False):
    """
    Serve audios as static files for html5 audio tag
    """
    # here is my custom filter which controls access to this view
    return serve(request, full_path, document_root, show_indexes)

def sound_download(request, sub_folder, filename):
    """
    Provides audio file downloads
    """
    path_to_mp3 = 'media/sound/'

    fsock = open(path_to_mp3+sub_folder+'/'+filename, 'rb')
    response = HttpResponse(fsock, mimetype='audio/mpeg')
    response['Content-Type'] = 'audio/mp3'
    response['Content-Disposition'] = "attachment; filename=%s" % \
        (filename.replace(' ', '-'), )
    response['Content-Length'] = \
        os.path.getsize(path_to_mp3+sub_folder+'/'+filename)
    return response

urls.py

url(r'^sound_download/(?P<sub_folder>[\w-]+)/(?P<filename>[\w\s\.-]+)/$',views.sound_download, name=u'Get lead audios history'),
url(r'^media/sound/(?P<path>[\w\s\./_-]+)$', views.customize_media_serving, {'document_root': settings.MEDIA_ROOT, }),

html template

<!-- audio is an instance of the model Audio -->
    <tr>
        <td>{{ audio.call_date }}</td>
        <td>
        <audio preload="auto" controls="" class="history_audio_player">
            <source type="audio/mpeg" src="/media/sound/{{ audio.file_link }}" />
            {% trans "This text displays if your Internet browser doesn't support the audio player." %}
        </audio>
        <a href="/sound_download/{{ audio.file_link }}" class="audio_download">
            <img src="{{ STATIC_URL }}img/download.png" style="height:30px;"/>
        </a>
        </td>
    </tr>

All this above works fine.

  1. Files could be downloaded by the link
  2. Links could be accessed by predefined groups of users
  3. HTML5 audio player is correctly displayed with all elements of control. The record is played not only once (you don't need to reload the page). User can operate the progress bar choosing the time of the audio. Time displays correct after the playback

The only problem I have is when I run

python manage.py collectstatic

all files are copied in the static dir

The reason for the files are not in common directory 'static' is that they will be uploading during the site is on the fly.

I guess there is a better solution. Mine seems to be not fully correct. It is like a bicycle with the back rectangle wheel: it is moving but something is wrong. I appriciate any suggestions.

P.S. yes, I've read some issues about serving mp3 files and audio tag Not able to serve mp3 files in django
Django: Serving a Download in a Generic View
as you can see these two helped a bit

Community
  • 1
  • 1
BernarditoLuis
  • 157
  • 3
  • 12
  • You really, really should not be trying to serve these via Django. – Daniel Roseman Jan 23 '15 at 16:02
  • I suggest that you should put .mp3 files to Amazon S3 using `django-storage` https://django-storages.readthedocs.org/en/latest/ – Vinta Jan 23 '15 at 17:49
  • In addition to the excellent advice already given, please consider upgrading to a secure version of Django. 1.4 is severely outdated. – souldeux Jan 23 '15 at 19:36
  • Thank you all for your responses! – BernarditoLuis Jan 25 '15 at 18:10
  • @DanielRoseman so I should organize it somehow using my nginx settings. Am I right? And these mp3s would be static. Next problem is to download the record by simple click. – BernarditoLuis Jan 25 '15 at 18:30
  • @Vinta This might be a good idea but not for me. It's not that easy to get agree on this question with the client. Better to have these audios on the server of mine employer. – BernarditoLuis Jan 25 '15 at 18:31
  • @souldeux Yes the system is not too big now. Could you share your experience on how hard is the upgrade? – BernarditoLuis Jan 25 '15 at 18:32
  • Very simple, very easy. I admit I only have experience upgrading from 1.5 & 1.6, so 1.4>1.7 may be tougher. – souldeux Jan 26 '15 at 16:28

0 Answers0