OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Add song to Playlist not working Django music App

  • Thread starter Thread starter Federico Monetti
  • Start date Start date
F

Federico Monetti

Guest
i'm making a music streaming website (it's my first project on Django). i'm making the view to add a song to a specific playlist but is not working (i always get the error "failed to add song to playlist") and the songs are not added to plsylists. how can i fix it?

html:

Code:
{% if my_playlists %}
        <p style="">Add This Song To Your Playlist</p>
        {% for playlist in my_playlists %}
            <a class="left-panel-btn" id="D_{{playlist.playlist_id}}" onclick="sendPostRequestPlaylistSong(this)">{{playlist.playlist_name}}</a><br>
        {% endfor %}
{% else %}
        <p style="">You don't have any Playlist.</p>
        <a class="create-p" onclick="$('#divId').css({display: 'none'}); document.getElementById('modal-wrapper-playlist').style.display='block'"><i class="fas fa-plus"></i> Create Playlist</a>
{% endif %}

javascript function:

Code:
function sendPostRequestPlaylistSong(el) {
        // alert("Song ID: "+song_id_for_playlist+" | Playlist ID: "+el.id);
        var data = song_id_for_playlist + "|" + el.id;
        $.ajax({
            "url": "{% url 'music:addSongToPlaylist' %}",
            "type": "POST",
            "data": { 'data': data, 'csrfmiddlewaretoken': '{{ csrf_token }}' },
            success: function(response) {
            alert("Song added to your playlist");
            location.reload();},
            error: function(xhr, status, error) {
            alert("Failed to add song to playlist.");}
            });
        var div = $("#divId");
        div.css({
            transition: "0.3s",
            display: "none"
        });
    }

views.py:

Code:
def addSongToPlaylist(request):
user = request.user
if request.method == "POST" and user.is_authenticated:
    data = request.POST['data']
    if data:
        song_id, playlist_id = data.split("|")
        song_id = song_id[0][2:]
        playlist_id = playlist_id[1][2:]
        currPlaylist = Playlist.objects.filter(playlist_id=playlist_id, user=request.user).first()
        song = Song.objects.filter(song_id=song_id).first()
        if song not in currPlaylist.songs.all():
            currPlaylist.songs.add(song)
            currPlaylist.plays = currPlaylist.songs.count()
            currPlaylist.save()
            messages.success(request, "Song added successfully")
        return HttpResponse("Successfull")
else:
    return redirect("users:login")

models.py:

Code:
class Playlist(models.Model):
playlist_id = models.AutoField(primary_key=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
playlist_name = models.CharField(max_length=50, default="name")
image = models.ImageField(upload_to="playlist_images/", validators=[FileExtensionValidator(allowed_extensions=['jpeg', 'jpg', 'png'])], blank=True)
plays = models.IntegerField(default=0)
songs = models.ManyToManyField(Song, related_name='playlist')
slug = models.SlugField()

<p>i'm making a music streaming website (it's my first project on Django). i'm making the view to add a song to a specific playlist but is not working (i always get the error "failed to add song to playlist") and the songs are not added to plsylists. how can i fix it?</p>
<p>html:</p>
<pre><code>{% if my_playlists %}
<p style="">Add This Song To Your Playlist</p>
{% for playlist in my_playlists %}
<a class="left-panel-btn" id="D_{{playlist.playlist_id}}" onclick="sendPostRequestPlaylistSong(this)">{{playlist.playlist_name}}</a><br>
{% endfor %}
{% else %}
<p style="">You don't have any Playlist.</p>
<a class="create-p" onclick="$('#divId').css({display: 'none'}); document.getElementById('modal-wrapper-playlist').style.display='block'"><i class="fas fa-plus"></i> Create Playlist</a>
{% endif %}
</code></pre>
<p>javascript function:</p>
<pre><code>function sendPostRequestPlaylistSong(el) {
// alert("Song ID: "+song_id_for_playlist+" | Playlist ID: "+el.id);
var data = song_id_for_playlist + "|" + el.id;
$.ajax({
"url": "{% url 'music:addSongToPlaylist' %}",
"type": "POST",
"data": { 'data': data, 'csrfmiddlewaretoken': '{{ csrf_token }}' },
success: function(response) {
alert("Song added to your playlist");
location.reload();},
error: function(xhr, status, error) {
alert("Failed to add song to playlist.");}
});
var div = $("#divId");
div.css({
transition: "0.3s",
display: "none"
});
}
</code></pre>
<p>views.py:</p>
<pre><code>def addSongToPlaylist(request):
user = request.user
if request.method == "POST" and user.is_authenticated:
data = request.POST['data']
if data:
song_id, playlist_id = data.split("|")
song_id = song_id[0][2:]
playlist_id = playlist_id[1][2:]
currPlaylist = Playlist.objects.filter(playlist_id=playlist_id, user=request.user).first()
song = Song.objects.filter(song_id=song_id).first()
if song not in currPlaylist.songs.all():
currPlaylist.songs.add(song)
currPlaylist.plays = currPlaylist.songs.count()
currPlaylist.save()
messages.success(request, "Song added successfully")
return HttpResponse("Successfull")
else:
return redirect("users:login")
</code></pre>
<p>models.py:</p>
<pre><code>class Playlist(models.Model):
playlist_id = models.AutoField(primary_key=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
playlist_name = models.CharField(max_length=50, default="name")
image = models.ImageField(upload_to="playlist_images/", validators=[FileExtensionValidator(allowed_extensions=['jpeg', 'jpg', 'png'])], blank=True)
plays = models.IntegerField(default=0)
songs = models.ManyToManyField(Song, related_name='playlist')
slug = models.SlugField()
</code></pre>
 

Latest posts

Top