Добавить песню в плейлист не работает Django music App

Я делаю сайт для прослушивания музыки (это мой первый проект на Django). Я делаю представление для добавления песни в определенный плейлист, но оно не работает (я всегда получаю ошибку "failed to add song to playlist"), и песни не добавляются в плейлисты. Как я могу это исправить?

HTML:

{% 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 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:

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")


def playlist(request, playlist_id):
user = request.user
if user.is_authenticated:
    myPlaylists = Playlist.objects.filter(user=user)
    if request.method == "POST":
        song_id = request.POST["music_id"]
        playlist = Playlist.objects.filter(playlist_id=playlist_id).first()
        if song_id in playlist.songs.all():
            playlist.songs.remove(song_id)
            playlist.plays -= 1
            playlist.save()
        message = "Successfull"
        print(message)
        return HttpResponse(json.dumps({'message': message}))
    else:
        images = os.listdir("media/playlist_images")
        currPlaylist = Playlist.objects.filter(playlist_id=playlist_id).first()
        songs = currPlaylist.songs
        playlistSongs = [currPlaylist.songs.all()]
        recommendedSingers = []
        return render(request, "music/playlist.html", {'playlistInfo': currPlaylist,
                                                       'playlistSongs': playlistSongs,
                                                       'myPlaylists': myPlaylists,
                                                       'recommendedSingers': recommendedSingers})

models.py:

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()
Вернуться на верх