In this post, we’ll walk through how to create a simple web application in Django that displays a list of music tracks and allows users to play them as a playlist. We’ll define a Music model, set up the views and templates, and use JavaScript to enable playlist functionality.
Step 1: Set Up the Django Project and App
Start by creating a Django project and app. If you don’t have one already, you can create them with the following commands:
django-admin startproject musicapp cd musicapp python manage.py startapp music
Add the music app to the INSTALLED_APPS in your settings.py:
INSTALLED_APPS = [ ... 'music', ]
Step 2: Define the Music Model
In the models.py of your music app, create the Music model:
from django.db import models class Music(models.Model): title = models.CharField(max_length=200) description = models.TextField(blank=True, null=True) audio_file = models.FileField(upload_to='music/') def __str__(self): return self.title
After defining the model, run the migrations:
python manage.py makemigrations python manage.py migrate
Step 3: Create a Simple Form for Uploading Music
To populate the database with some music tracks, create a MusicForm in forms.py:
from django import forms from .models import Music class MusicForm(forms.ModelForm): class Meta: model = Music fields = ['title', 'description', 'audio_file']
Step 4: Set Up Views for Displaying and Uploading Music
Create views in views.py for listing music tracks and adding new ones:
from django.shortcuts import render, redirect from .models import Music from .forms import MusicForm def music_list(request): musics = Music.objects.all() return render(request, 'music/music_list.html', {'musics': musics}) def upload_music(request): if request.method == 'POST': form = MusicForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('music_list') else: form = MusicForm() return render(request, 'music/upload_music.html', {'form': form})
Step 5: Configure URLs
In urls.py of the music app, add routes for the views:
from django.urls import path from . import views urlpatterns = [ path('', views.music_list, name='music_list'), path('upload/', views.upload_music, name='upload_music'), ]
Include these URLs in your project’s urls.py:
from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('music.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Add MEDIA_URL and MEDIA_ROOT to your settings.py for serving uploaded audio files:
MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media'
Step 6: Create Templates
music_list.html
Create a template to display the list of music and implement a playlist using HTML and JavaScript:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Music Playlist</title> </head> <body> <h1>Music Playlist</h1> <ul id="music-list"> {% for music in musics %} <li data-audio="{{ music.audio_file.url }}"> <strong>{{ music.title }}</strong> - {{ music.description }} </li> {% endfor %} </ul> <audio id="audio-player" controls></audio> <script> const audioPlayer = document.getElementById('audio-player'); const musicList = document.getElementById('music-list'); const tracks = musicList.querySelectorAll('li'); let currentTrack = 0; function playTrack(index) { const track = tracks[index]; audioPlayer.src = track.getAttribute('data-audio'); audioPlayer.play(); } // Automatically play the next track when the current one ends audioPlayer.addEventListener('ended', () => { currentTrack = (currentTrack + 1) % tracks.length; // Loop back to the first track playTrack(currentTrack); }); // Play the first track on page load if (tracks.length > 0) { playTrack(currentTrack); } </script> </body> </html>
upload_music.html
Create a simple form template for uploading music:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Upload Music</title> </head> <body> <h1>Upload Music</h1> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> <a href="{% url 'music_list' %}">Back to Playlist</a> </body> </html>
Step 7: Test the Application
Run the Django development server:
python manage.py runserver
Visit http://127.0.0.1:8000/ to see the music playlist and play tracks.
Visit http://127.0.0.1:8000/upload/ to upload new tracks.
Conclusion
With this guide, you’ve built a basic Django web application to manage and play a music playlist. You can expand this project by adding features like user authentication, playlists for specific users, or support for streaming large audio files. The simple JavaScript solution provided allows users to enjoy their music tracks as a continuous playlist.