How to pass Audio file from model to Template in Django?

Hi Django Developer,

I’ve just started out with Django and have tried making an audio player application website.

I’ve created a model for succesfully uploading a file, taking a input file name, and storing it in a media folder in within my app directory:

class DemoMCall(models.Model):
    rid = models.PositiveBigIntegerField(primary_key=True)
    info_agent = models.CharField(max_length=200, blank=True, null=True)
    tstamp = models.DateTimeField()
    call_time = models.BigIntegerField(blank=True, null=True)
    audio_file = models.FileField( upload_to =  'uploads/' )
    type = models.PositiveIntegerField(blank=True, null=True)

    class Meta:
        #managed = False
        db_table = 'demo_m_call'

In my Template I then have a for loop set up to create list of audio players for every different audio track.:

    <tbody>
         {% for record in records  %}
            <tr>
              <th scope="row">{{ record.rid }}</th>
              <td>{{ record.info_agent }}
              <td>{{ record.info_customer }}
              <td>{{ record.tstamp }}
              <td>{{ record.date_call }}
              <td>{{ record.time_curr_call }}
              <td>{{ record.call_time }}
              <td>{{ record.type}}
              <td>{{ record.audio_file}}
              <td> <audio controls id="player">
                <source src="{{record.audio_file.url}}" type="audio/wav">
                Your browser does not support the audio element.
              </audio>
             </tr>
           {% endfor %}
    </tbody>
  </table>
</body>
</html>

This is how my views are set up:

def wav_audio(request):    
        
        rec = DemoMCall.objects.all()          

        return render(request, 'qualityManagement/audio.html' , {'rec': rec }  )

I’ve been going crazy for the last day or so trying to figure out what is causing it not to work. I spent a lot of time trying to get it to source the correct path for the files but even though it seems to do that the files still can’t be played.

Thankful for any help I can receive! Sorry for any eventual formatting errors and such…

In settings.py:

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

In url.py:

urlpatterns = [
    path("Call_listing/", views.record_filter , name="Call_Listing"),    
    ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

It works :grinning:

                <td> <audio controls >
                  <source src=" {% if record.audio_file %} {{ record.audio_file.url }} {% endif %}" type="audio/wav">
                  Your browser does not support the audio element.
                </audio>

how to call func wav_audio in urls? can you show me your urls.py?