Creating An Api For A Music App Designed To Store Playlists And Maintain The Music Library Using Django Web Framework
MUSIC APP
Table of contents
No headings in the article.
STEP 1
Installing a music player, when it comes to mind seems like a hard task but it gets quite easy with time. There are some basic prerequisites for creating a music player, the basic apps needed are Python, Django and pillow.
To install the following prerequisites you make use of the command prompt or terminal by running the following command. That's if you don't have it installed already
pip install python
After doing that the next step for you is to create a virtual environment, virtual environments act as containers for storing your various projects. There is no limit to the number of virtual environments that can be created, you can create as many as you like.
The code for executing this command is
virtualenv v(name of your virtual environment)
e.g virtualenv vmusic
I used that for mine,dosen't have to be the same be creative
In case you don't have it installed you can download it by running the following command
pip install virtualenv v(name of your virtual environment)
After creating my virtual environment, the next thing I did was activate it. A virtual environment can only be used if it is activated, if it isn't it is more or less just a directory.
I activated my virtual environment by running the following command
Scripts\activate.bat
NOTE:This is for Windows users only
Once activated you should see something like this on your command prompt or terminal
(vmusic) C:\Users\USER\vmusic
Once my virtual environment was activated I then downloaded the Django app and the pillow app. Django is a web framework that makes use of the MVT (Model View Template) approach. It makes backend web development relatively easy and as easy as it is, it comes with inbuilt tools which enable you to carry out your tasks effectively.
While on the other hand pillow is an app that is basically for images, it enables you to add, remove and modify images in your app.
After doing that you run the following commands to install Django and pillow
pip install django
pip install pillow
OR
pip install django pillow
It should give you this
(vmusic) C:\Users\USER\vmusic> pip install django pillow
Collecting django
Using cached Django-3.2.16-py3-none-any.whl (7.9 MB)
Collecting pillow
Using cached Pillow-8.4.0-cp36-cp36m-win_amd64.whl (3.2 MB)
Collecting sqlparse>=0.2.2
Using cached sqlparse-0.4.3-py3-none-any.whl (42 kB)
Collecting pytz
Using cached pytz-2022.6-py2.py3-none-any.whl (498 kB)
Collecting asgiref<4,>=3.3.2
Using cached asgiref-3.4.1-py3-none-any.whl (25 kB)
Collecting typing-extensions
Using cached typing_extensions-4.1.1-py3-none-any.whl (26 kB)
Installing collected packages: typing-extensions, sqlparse, pytz, asgiref, pillow, django
Successfully installed asgiref-3.4.1 django-3.2.16 pillow-8.4.0 pytz-2022.6 sqlparse-0.4.3 typing-extensions-4.1.1
This shows that your Django app has been successfully installed alongside your pillow app. The next step is to start your project using the command
django-admin startproject (name of your project)
(vmusic) C:\Users\USER\vmusic> django-admin startproject MusicPlayer
After doing that I moved into that directory which I just created MusicPlayer
In case you don't know how you move into a directory by using the command cd MusicPlayer
(vmusic) C:\Users\USER\vmusic> cd MusicPlayer
Once you have moved into your directory it should appear like this
Before running your server you need to create your app just like you created your project. The command for this is
django-admin startapp (name of your app)
I just called mine app
(vmusic) C:\Users\USER\vmusic\MusicPlayer> django-admin startapp App
You can now run your server
The command to run your server is python manage.py runserver
(vmusic) C:\Users\USER\vmusic\MusicPlayer> python manage.py runserver
If your server is fully running, you should get something like this
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
December 07, 2022 - 15:26:24
Django version 3.2.16, using settings 'MusicPlayer.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Then you are going to copy your local host server which is http://127.0.0.1:8000/
and paste, then run it on any of your browsers. If it runs well it means that you have successfully installed your Django app.
STEP 2
Step two is the most vital, as it will enable you to control your music app library and also control who gets access to it. The first thing I did was import the folder created containing my project into my text editor. I made use of the sublime text editor but u can also make use of vs code. Any text editor will do as long as it does the work
Here is a pic of my workspace
After importing my folder to my text editor or workspace, I went to register my app in settings.py in my workspace as seen below. The name of my app is App so I just added it to the list of installed apps
Moving into my app's directory was the next thing that I did. I executed that on my command prompt by using the command
cd (name of your App)
In my case it was cd app
Giving me this on my cmd
Below is a picture of me executing the code on my command prompt and also displaying the result
CODE :(vmusic) C:\Users\USER\vmusic\MusicPlayer> cd App
RESULT: (vmusic) C:\Users\USER\vmusic\MusicPlayer\App>
The next thing I did was to create a static and template folder, the template folder will house the HTML files while the static folder will house the CSS, Javascript and other static files.
To create a folder or directory, you run this code
mkdir templates
mkdir static
It would be displayed like this on your command prompt
(vmusic) C:\Users\USER\vmusic\MusicPlayer\App> mkdir templates
(vmusic) C:\Users\USER\vmusic\MusicPlayer\App> mkdir static
Once done with that, you should see it on your workspace like this
You are going to create a new file in your template folder, the new file will be called index.html. Then we are going to copy a particular code and paste it into it
Below is a sample of the code to be placed in the index.html file
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>
My Music Player
</title>
<link href="https://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/mediaelement/4.2.7/mediaelementplayer.min.css" rel="stylesheet"/>
<link href="{% static './style.css' %}" rel="stylesheet"/>
</head>
<body>
<!-- partial:index.partial.html -->
<html>
<head>
<meta charset="utf-8"/>
<title>
Flat music player
</title>
</head>
<body>
<div class="contain">
<div class="container">
<div class="music-player">
{% for item in page_obj %}
<div class="cover">
<img alt="" src="{{item.image.url}}"/>
</div>
<div class="titre">
<h3>
{{item.artist}}
</h3>
<h1>
{{item.title}}
</h1>
</div>
<center><a href="{% if page_obj.has_previous %}?page={{ page_obj.previous_page_number }}{% endif %}"><i class="fa fa-step-backward fa-2x"></i></a> <a href="{% if page_obj.has_next %}?page={{ page_obj.next_page_number }} {% endif %}"><i class="fa fa-step-forward fa-2x"></i></a></center>
<div class="lecteur">
<audio class="fc-media" style="width: 100%;">
<source src="{% if item.audio_file %}{{item.audio_file.url}} {% else %} {{item.audio_link}} {% endif %}" type="audio/mp3"/>
</audio>
</div>
{% endfor %}
</div>
</div>
</div>
</body>
</html>
<!-- partial -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mediaelement/4.2.7/mediaelement-and-player.min.js">
</script>
<script src="{% static './script.js' %}">
</script>
</body>
</html>
In the code above I used Bootstrap, It was imported from the CND link as seen in the head tag. It is going to be used to generate HTML attributes for the MusicPlayer.
In the static folder that you just created, you are going to create two new files, the two files are going be called script.js and style.css
You are going to add this code in the script.js
(vmusic) C:\Users\USER\vmusic\MusicPlayer\App> mkdir templatesa var audio = {
init: function() {
var $that = this;
$(function() {
$that.components.media();
});
},
components: {
media: function(target) {
var media = $('audio.fc-media', (target !== undefined) ? target : 'body');
if (media.length) {
media.mediaelementplayer({
audioHeight: 40,
features : ['playpause', 'current', 'duration', 'progress', 'volume', 'tracks', 'fullscreen'],
alwaysShowControls : true,
timeAndDurationSeparator: '<span></span>',
iPadUseNativeControls: true,
iPhoneUseNativeControls: true,
AndroidUseNativeControls: true
});
}
},
},
};
audio.init();
The code above is the javascript file that determines how our music is going to be played when a link for the music stored in the database is passed into the music player. The code controls how the music is used
In the style. CSS, you are going to edit and add this code to it
*:focus{
outline: none;
}
html {
background: #f2f2f2;
}
body {
margin: 0;
font-family: "Raleway",sans-serif;
}
h1 {
margin: 0;
font-size: 33px;
color: #fff;
padding: 0 10%;
}
h3 {
margin: 0;
font-size: 17px;
font-weight: 500;
color: #ccc;
padding: 0 10%;
}
.container {
display: block;
width: 100%;
height: 750px;
margin: auto;
overflow: hidden;
background-image: url("https://mariongrandvincent.github.io/HTML-Personal-website/img-codePen/bg-music-player.jpg");
background-repeat: repeat;
background-size: cover;
}
.music-player {
display: block;
position: relative;
width: 400px;
height: 570px;
margin: auto;
margin-top: 6%;
border-radius: 0 0 10px 10px;
background: transparent linear-gradient(to bottom,rgba(10,11,31,0.9) 50%,rgb(10,11,31) 70%) repeat scroll 0 0;
box-shadow: 1px 10px 20px 5px #222;
}
.cover {
float: left;
width: 100%;
height: 66%;
}
.cover img {
display: block;
position: absolute;
top: 8%;
left: 14%;
width: 70%;
margin: auto;
text-align: center;
}
.titre {
float: left;
width: 100%;
}
.lecteur {
width: 100%;
display: block;
height: auto;
position: relative;
float: left;
}
.mejs__button>button:focus {
outline: 0px dotted #999;
}
.mejs__container {
position: relative;
background-color: transparent;
min-width: auto !important;
}
.mejs__controls {
padding: 0 10%;
background: transparent !important;
display: block;
position: relative;
}
.mejs__controls div {
display: block;
float: left;
position: relative;
}
.mejs__controls .mejs__playpause-button {
position: absolute !important;
right: 8%;
bottom: 95%;
width: 40px;
}
.mejs__controls .mejs__playpause-button button {
display: block;
width: 40px;
height: 40px;
padding: 0;
border: 0;
font-family: FontAwesome;
font-size: 23px;
color: #5bbb95;
background: transparent;
padding: 0;
margin: 0;
}
.mejs__controls .mejs__play button:before{
content:"\f04b";
}
.mejs__controls .mejs__pause button:before{
content:"\f04c";
}
.mejs__controls .mejs__volume-button button {
display: block;
width: 40px;
height: 40px;
padding: 0;
border: 0;
font-family: FontAwesome;
font-size: 20px;
color: #5bbb95;
background: transparent;
margin: 0;
padding: 0;
}
.mejs__controls .mejs__mute button:before {
content: "\f028";
}
.mejs__controls .mejs__unmute button:before {
content: "\f026";
}
.mejs__controls .mejs__time {
width: 100%;
margin-top: 7%;
margin-bottom: 3%;
color: #fff;
height: auto;
padding: 0;
overflow: visible;
min-width: 100%;
}
.mejs__controls .mejs__time span {
font-size: 15px;
}
.mejs__controls span.mejs__duration {
float: right;
text-align: right;
color: #ccc;
}
.mejs__controls span.mejs__currenttime {
font-weight: 700;
float: left;
}
.mejs__controls .mejs__time-rail {
width: 100%;
margin: 0;
}
.mejs__controls .mejs__time-rail span {
position: absolute;
top: 0;
width: 100%;
height: 4px;
border-radius: 50px;
cursor: pointer;
}
.mejs__controls .mejs__time-rail .mejs__time-loaded {
background: rgba(255,255,255,0.2);
}
.mejs__controls .mejs__time-rail .mejs__time-float {
display: none;
top: -40px;
width: 40px;
height: 25px;
margin-left: 0px;
text-align: center;
font-size: 10px;
background: #fff;
border: 0;
}
.mejs__controls .mejs__time-rail .mejs__time-float-current {
display: block;
position: relative;
top: 0;
margin: 0;
line-height: 26px;
color: #100d28;
}
.mejs__controls .mejs__time-rail .mejs__time-float-corner {
top: auto;
bottom: -9px;
left: 50%;
width: 0;
height: 0;
border-top: 6px solid #fff;
border-right: 6px solid transparent;
border-left: 6px solid transparent;
}
.mejs__controls .mejs__time-rail .mejs__time-current {
background: #5BBB95 none repeat scroll 0 0;
}
.mejs__controls .mejs__time-handle {
display: none;
}
.mejs__controls .mejs__volume-button {
position: relative;
position: absolute !important;
top: 70px;
right: 25%;
width: 40px;
height: 40px;
}
.mejs__controls .mejs__horizontal-volume-slider {
display: block;
position: absolute !important;
position: relative;
top: 70px;
right: 10%;
width: 60px;
height: 4px;
margin-top: 18px;
border-radius: 50px;
line-height: 11px;
}
.mejs__controls .mejs__horizontal-volume-slider .mejs__horizontal-volume-total,
.mejs__controls .mejs__horizontal-volume-slider .mejs__horizontal-volume-current {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(255,255,255,0.1);
}
.mejs__controls .mejs__horizontal-volume-slider .mejs__horizontal-volume-current {
background: #fff;
}
This code determines how our HTML template looks and feels
Next, we import os to our setting.py in our workspace, we import it by adding the code below to the top of our setting.py. You are going to also have to edit some things there
import os
It should look like this
We are also going to define our static_root, media_root and media_url in our settings.py. What we are going to do is that we are going to copy the code below and paste it into our settings .py from our workspace and edit where needed
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_ROOT =os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
In our MusicPlayer directory, we are going to edit the url.py to this
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib.staticfiles.urls import static
urlpatterns = [
path('admin/', admin.site.urls),
]
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Go back to your App directory and create a new file called url.py. Here we are going to define the root URL that our Django project is going to be linked to.
After creating the new url.py file, add the following code to it
from django.conf import settings
from django.conf.urls.static import static
from django.urls import path, include
from . import views
app_name = "App"
urlpatterns = [
path("", views.index, name="index"),
]
In the above, we have defined all the URL patterns that our app is going to be linked to.
It also means that we have designed all the visitable links that our app has access to.
From our App directory, we are going to edit our models.py and add the following code to it
from django.db import models
# Create your models here.
class Song(models.Model):
title= models.TextField()
artist= models.TextField()
image= models.ImageField()
audio_file = models.FileField(blank=True,null=True)
audio_link = models.CharField(max_length=200,blank=True,null=True)
duration=models.CharField(max_length=20)
paginate_by = 2
def __str__(self):
return self.title
This code shows that we have defined our song model which represents a data table in our database storing our songs. The features of the class define the fields of the song table in our database
The next thing is to go to the view.py and edit and add the following code to it
from django.shortcuts import render, redirect
# imported our models
from django.core.paginator import Paginator
from . models import Song
def index(request):
paginator= Paginator(Song.objects.all(),1)
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
context={"page_obj":page_obj}
return render(request,"index.html",context)
What I simply did here was to import the following packages needed which are 'render', 'redirect', and 'paginator'. We also imported our class song from model.py.
Then we defined our index view function that controls how the index page works.
Finally, I then migrated my models to my database by using the following command on my command line in the root directory where I can find our python manage.py file
We are first going to migrate the app and changes made to our database by using the command
python manage.py makemigrationns
Then we are now going to migrate by using the command
python manage.py migrate
If your migrations were successful, you should see this on your command line
(vmusic) C:\Users\USER\vmusic\MusicPlayer> python manage.py migrate
Operations to perform:
Apply all migrations: App, admin, auth, contenttypes, sessions
Running migrations:
Applying App.0001_initial... OK
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying auth.0012_alter_user_first_name_max_length... OK
Applying sessions.0001_initial... OK
Although we have done that our work isn't finished we still have to register our songs in our admin.py. We do this by going to our admin.py in our workspace and adding the following code to it
from django.contrib import admin
from . models import Song
# Register your models here.
admin.site.register(Song)
Once this is done, the last thing to do is to create a superuser. Creating a superuser enables you to log into the Django admin login page.
You create a superuser by entering the code
python managae.py createsuperuser
Once that is done you will be prompted to enter your username, email and password. As this is done you can now log into the Django admin page by entering your password and username
However, you are going to first have to run your server.
You should see something like thing if you have successfully created your superuser
STEP 3
Finally, you are to log into the admin page and enter your details as seen below
The Django database should look like this after logging in
You can add soon by touching the button add by the song table in the above picture. If you were successful in doing that, you should get this
You can add as many songs as you like,
We have finally come to the end of this article, stay tuned for more on this channel