title: Django. How to serve mp3 files?
body: <p>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.</p>
  
  <p>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):<br></p>
  
  <p>models.py</p>
  
  <pre><code>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'
  </code></pre>
  
  <p>views.py</p>
  
  <pre><code>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
  </code></pre>
  
  <p>urls.py</p>
  
  <pre><code>url(r'^sound_download/(?P&lt;sub_folder&gt;[\w-]+)/(?P&lt;filename&gt;[\w\s\.-]+)/$',views.sound_download, name=u'Get lead audios history'),
  url(r'^media/sound/(?P&lt;path&gt;[\w\s\./_-]+)$', views.customize_media_serving, {'document_root': settings.MEDIA_ROOT, }),
  </code></pre>
  
  <p>html template</p>
  
  <pre><code>&lt;!-- audio is an instance of the model Audio --&gt;
      &lt;tr&gt;
          &lt;td&gt;{{ audio.call_date }}&lt;/td&gt;
          &lt;td&gt;
          &lt;audio preload="auto" controls="" class="history_audio_player"&gt;
              &lt;source type="audio/mpeg" src="/media/sound/{{ audio.file_link }}" /&gt;
              {% trans "This text displays if your Internet browser doesn't support the audio player." %}
          &lt;/audio&gt;
          &lt;a href="/sound_download/{{ audio.file_link }}" class="audio_download"&gt;
              &lt;img src="{{ STATIC_URL }}img/download.png" style="height:30px;"/&gt;
          &lt;/a&gt;
          &lt;/td&gt;
      &lt;/tr&gt;
  </code></pre>
  
  <p>All this above works fine.</p>
  
  <ol>
  <li>Files could be downloaded by the link</li>
  <li>Links could be accessed by predefined groups of users </li>
  <li>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</li>
  </ol>
  
  <p>The only problem I have is when I run </p>
  
  <pre><code>python manage.py collectstatic
  </code></pre>
  
  <p>all files are copied in the static dir</p>
  
  <p>The reason for the files are not in common directory 'static' is that they will be uploading during the site is on the fly.</p>
  
  <p>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>
  
  <p>P.S. yes, I've read some issues about serving mp3 files and audio tag
  <a href="https://stackoverflow.com/questions/11896454/not-able-to-serve-mp3-files-in-django">Not able to serve mp3 files in django</a> <br>
  <a href="https://stackoverflow.com/questions/2681338/django-serving-a-download-in-a-generic-view">Django: Serving a Download in a Generic View</a> <br>
  as you can see these two helped a bit</p>