Music Player Using Django

During a Python webinar, one of my students asked me about building a music player application using Django. I explored more about this topic and decided to help him. It not only sharpens your skills but also results in a practical app you can expand on later.

In this tutorial, I’ll walk you through how to build a fully functional music player with Django. We’ll cover everything from setting up your project to adding, listing, and removing songs, all stored in a database.

Let’s get in!

Steps to build a Music Player Application.

  • Python installed on your system (preferably Python 3.8+)
  • Basic knowledge of Django and Python
  • A code editor like VS Code or PyCharm
  • Familiarity with HTML and Bootstrap for styling (optional but recommended)

Check out Build a Chat App in Django

Step 1: Set Up Your Django Project and App

First, create a new Django project and an app inside it to hold your music player functionality.

# Create project
django-admin startproject musicplayer_project

# Navigate into project directory
cd musicplayer_project

# Create app
python manage.py startapp music

Add the music app to your project’s settings.py under INSTALLED_APPS:

INSTALLED_APPS = [
    # default apps...
    'music',
]

Step 2: Define the Song Model

We need a model to represent songs in our database. Each song will have a title, artist, and audio file.

Open music/models.py and add:

from django.db import models

class Song(models.Model):
    title = models.CharField(max_length=200)
    artist = models.CharField(max_length=200)
    audio_file = models.FileField(upload_to='songs/')

    def __str__(self):
        return f"{self.title} by {self.artist}"

This model stores song details and the audio file itself.

Run migrations to create the corresponding database table:

python manage.py makemigrations
python manage.py migrate

Read How to Deploy an AI Model with Django

Step 3: Configure Media Files

To serve audio files during development, configure media settings.

In settings.py add:

import os

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

In the project’s main urls.py, add media URL serving:

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # your url patterns here
]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Step 4: Create Forms to Add Songs

We want users to add songs via a web form.

Create music/forms.py:

from django import forms
from .models import Song

class SongForm(forms.ModelForm):
    class Meta:
        model = Song
        fields = ['title', 'artist', 'audio_file']

Read Compare Two Integers in Python Django

Step 5: Build Views for Listing and Adding Songs

In music/views.py, add views to display all songs and add new ones.

from django.shortcuts import render, redirect
from .models import Song
from .forms import SongForm

def song_list(request):
    songs = Song.objects.all()
    return render(request, 'music/song_list.html', {'songs': songs})

def add_song(request):
    if request.method == 'POST':
        form = SongForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect('song_list')
    else:
        form = SongForm()
    return render(request, 'music/add_song.html', {'form': form})

Step 6: Create URL Patterns

In music/urls.py, define URL routes:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.song_list, name='song_list'),
    path('add/', views.add_song, name='add_song'),
]

Include these URLs in the main urls.py:

from django.urls import path, include

urlpatterns = [
    path('', include('music.urls')),
    # other paths...
]

Check out Payment Gateway Integration with Django

Step 7: Design Templates with Bootstrap

Create a folder music/templates/music/ and add two HTML files.

song_list.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Music Player</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="container mt-4">
    <h1>My Music Player</h1>
    <a href="{% url 'add_song' %}" class="btn btn-primary mb-3">Add New Song</a>
    <ul class="list-group">
        {% for song in songs %}
        <li class="list-group-item">
            <strong>{{ song.title }}</strong> by {{ song.artist }}
            <audio controls class="float-end" style="max-width: 300px;">
                <source src="{{ song.audio_file.url }}" type="audio/mpeg">
                Your browser does not support the audio element.
            </audio>
        </li>
        {% empty %}
        <li class="list-group-item">No songs added yet.</li>
        {% endfor %}
    </ul>
</body>
</html>

add_song.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Add Song</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="container mt-4">
    <h1>Add a New Song</h1>
    <form method="post" enctype="multipart/form-data" class="mb-3">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit" class="btn btn-success">Add Song</button>
        <a href="{% url 'song_list' %}" class="btn btn-secondary">Back to List</a>
    </form>
</body>
</html>

Step 8: Run the Development Server and Test

Start your server:

python manage.py runserver

Open http://127.0.0.1:8000/ in your browser. You’ll see your music player app, where you can add songs and play them directly.

You can refer to the screenshot below to see the output:

django music player
django music app

Read How to Add Items to Cart in Django in Python?

Alternative Method: Use Django REST Framework for a Music API

If you prefer building a RESTful API backend for a music player, Django REST Framework (DRF) is a great choice. You can expose endpoints for CRUD operations on songs and build a frontend with React or any other framework.

Here’s a quick overview:

  • Install DRF: pip install djangorestframework
  • Create serializers for the Song model
  • Build API views and routes
  • Consume the API in a frontend app

This method is more flexible for larger apps or mobile integrations, but requires more setup.

Building a music player with Django is a rewarding project that combines models, forms, file handling, and frontend integration. The approach I shared is simple to expand; you can add user authentication, playlists, or even streaming features next.

If you’re new to Django or want to level up your skills, building projects like this is the best way to learn. I hope this guide helps you create your music player app effortlessly!

You may also read other Django-related articles:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.