In this tutorial, we will be building a music-sharing app using Django. In this app, you will be able to create, delete, update, and also display songs. Here are a few screenshots of the complete app.
Now to begin we first need to install Django which will be our primary web server. To install Django run the command below.
pip3 install django
After installing Django now run the command below which will create our base project.
django-admin startproject django_music
The above command will create a folder named django_music , cd into the folder and run the command below which now create our app.
python3 manage.py startapp music
Next, we need to register our app. In the settings.py file add the following.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'music',
]
Now let’s create routes for our app, to do this add the following in the urls.py file.
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('music.urls')),
]
Now let’s move to our music folder and create models for our app. Inside the models.py file add the following.
from django.db import models
from django.utils import timezone
class Music(models.Model):
title = models.CharField(max_length=200)
artist = models.CharField(max_length=200)
category = models.CharField(max_length=30)
upload_date = models.DateTimeField(default=timezone.now)
song = models.FileField(upload_to='')
def __str__(self):
return self.title
The above code will create a database with the values above where our data will be stored. Next, we need to create forms that will be used to accept user music uploads. In the forms.py file add the following.
from django import forms
from . models import Music
class MusicUploadForm(forms.ModelForm):
class Meta:
model = Music
fields = ["title","artist", "category","song"]
Views
Our form is now ready, it will serve both music upload and update as we will see later. In the views.py inside the music folder add the following. We first begin with the music upload view.
from django.shortcuts import render, redirect,get_object_or_404
from django.views.generic import DetailView, DeleteView, UpdateView, ListView, CreateView
from . models import Music
from . forms import MusicUploadForm
class MusicCreateView(CreateView):
model = Music
success_url = "/"
template_name = 'music/music_create.html'
fields = ['title', 'artist','category','song']
Next, we will create the list view which will list all the songs uploaded on the site.
class MusicListView(ListView):
model = Music
template_name = 'music/music_list.html'
context_object_name = 'songs'
ordering = ['-upload_date']
Our app also has a search functionality in which you can search by song title. Here is the search view in the code below.
def search(request):
if request.method == "POST":
query = request.POST.get('title', None)
if query:
results = Music.objects.filter(title__contains=query)
return render(request, 'music/search.html',{'songs':results})
return render(request, 'music/search.html')
Next is the delete view which will handle all the delete functionalities.
class MusicDeleteView(DeleteView):
template_name = "music/music_delete.html"
success_url = "/"
model = Music
Now we need to have a detailed view of the songs listed on the home page, here is the detail view below.
class MusicDetailView(DetailView):
template_name = "music/music_detail.html"
model = Music
Finally, we need to create our update view where users can update their work.
def music_update(request, pk):
obj = get_object_or_404(Music, pk=pk)
form = MusicUploadForm(request.POST or None, instance=obj)
if form.is_valid():
form.save()
return redirect('/')
context = {
'form':form
}
return render(request, 'music/music_update.html',context)
Now we are done with our views, let’s now create routes for our app. Inside the music folder create a file called urls.py . Inside the file add the code below.
from django.urls import path
from . import views
from . views import (
MusicCreateView,
music_update,
MusicDeleteView,
MusicListView,
MusicDetailView,
)
urlpatterns = [
path('',MusicListView.as_view(),name="music-list"),
path('search',views.search,name="search"),
path('create',MusicCreateView.as_view(),name="music-create"),
path('music_detail/<int:pk>/',MusicDetailView.as_view(),name="music-detail"),
path('update/<int:pk>/',views.music_update, name="music-update"),
path('delete/<int:pk>/',MusicDeleteView.as_view(), name="music-delete"),
]
Templates
Now let’s create templates that we will use to display our app on a browser. Inside the music folder create a folder called templates and inside the templates folder create a folder called music. [music/templates/music/]. And now inside the music let’s create a file called base.html , this will be our base layout template from which other templates will inherit. Add the code below inside the base.html file.
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ" crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container">
<a class="navbar-brand" href="{% url 'music-list' %}">Music App</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-nav">
<div class="nav-item ml-auto">
<a class="nav-item nav-link" href="{% url 'search'%}">Search</a>
</div>
<div class="nav-item">
<a class="nav-item nav-link" href="{% url 'music-create' %}">New Music</a>
</div>
</div>
</div>
</nav>
<div class="container" id="app">
{% block content %}
{% endblock %}
</div>
<script src="{% static 'js/jquery.min.js' %}"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ENjdO4Dr2bkBIFxQpeoTz1HIcje39Wm4jDKdf19U8gI4ddQ3GYNS7NTKfAdVQSZe" crossorigin="anonymous"></script>
</body>
</html>
Now let’s create our music upload template, create a file called music_create.html and add the following.
{% extends 'music/base.html' %}
{% block content %}
</br>
<div class="container">
<div class="row justify-content-center">
<div class="col-md-6">
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<h1 class="text-center mb-4">Upload a Song</h1>
{{ form.as_p }}
<button class="btn btn-outline-info btn-block mt-4" type="submit">Upload</button>
</form>
</div>
</div>
</div>
{% endblock content %}
Next, we need to create the list template which will display all the songs uploaded. Create a file called music_list.html and add the following.
{% extends 'music/base.html' %}
{% block content %}
</br>
<div class="container">
<div class="row row-cols-1 row-cols-md-4">
{% for item in songs %}
<div class="col mb-4">
<div class="card h-100">
<div class="card-body">
<h5 class="card-title">{{ item.title }}</h5>
<p class="card-text">Artist: {{ item.artist }}</p>
<p class="card-text">Category: {{ item.category }}</p>
<p class="card-text">Uploaded on: {{ item.upload_date }}</p>
<audio controls style="max-width:100%;">
<source src="{{ item.song.url }}" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
</div>
<div class="card-footer">
<a href="{% url 'music-detail' item.id %}" class="btn btn-outline-info">View Details</a>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
{% endblock content %}
Next is the search template which we be used to search through the database and display the data. Create a file called search.html and add the following.
{% extends 'music/base.html'%}
{% block content %}
<div class="center_journal">
<h1>Search </h1>
</div>
<div>
<form method="POST">
{% csrf_token %}
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"></span>
</div>
<input type="text" class="form-control" name="title">
<button type="submit" class="btn btn-dark">Search</button>
</div>
</form>
</div>
</br>
<div class="container">
<div class="card-deck">
{% for item in songs %}
<div class="card mb-4">
<div class="card-body">
<h5 class="card-title">Song : {{ item.title }}</h5>
<p class="card-text">Song by : {{ item.artist }}</p>
<p class="card-text"> Category : {{ item.category }}</p>
<p class="card-text">{{ item.upload_date }}</p>
<audio controls>
<source src="{{ item.song.url }}" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
</div>
</div>
{% endfor %}
</div>
</div>
{% endblock content %}
Next, we need to create a detail template where users can have more information displayed on a certain song. Create a file called music_detail.html and add the following.
{% extends 'music/base.html' %}
{% block content %}
</br>
<div>
<h1>Song Title : {{ object.title }}</h1>
<h12>The video was uploaded on {{ object.upload_date }}</h12>
<p>Song by :{{ object.artist }}</p>
<p>Category : {{ object.category }}</p>
<div>
<a class="btn btn-secondary btn-sm mt-1 mb-1" href="{% url 'music-update' object.id %}">Update</a>
<a class="btn btn-danger btn-sm mt-1 mb-1" href="{% url 'music-delete' object.id %}">Delete</a>
</div>
<audio controls>
<source src="{{ object.song.url }}" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
</div>
{% endblock content %}
Now we need to create an update template where users can update their content, create a file called music_update.html and add the following.
{% extends 'music/base.html' %}
{% block content %}
</br>
<div>
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<h1>Upload a video</h1>
{{ form.as_p }}
<button class="btn btn-outline-info" type="submit">Upload</button>
</form>
</div>
{% endblock content %}
Finally, we need to delete our songs, and here is the template to achieve that. Create a file called music_delete.html and add the code below.
{% extends 'music/base.html'%}
{% block content %}
</br>
<div style="margin-top: 1%;">
<form method="POST">
{% csrf_token %}
<h3>Are you sure you want to delete the video {{ object.title }} ?</h3>
<button type="submit" class="btn btn-primary">Confirm Delete</button>
</form>
</div>
{% endblock content %}
Finally, the moment of truth, run the command below to create our models and migrate our data. In your terminal enter the following.
pythhon3 manage.py makemigrations
After successful execution of the command above run the next one below to migrate the data.
pip3 manage.py migrate
Finally, run the command below to start the server.
python3 manage.py runserver
After the above command is executed, your app should be accessible in the browser at the address shown below.
http://127.0.0.1:8000
There you have it, you have just built a music-sharing app using Django. Thanks for reading.
Pingback: How to Build A Language Translator App Using Django - bytexplain