You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django音乐网站取消收藏歌曲异常及红心状态同步求助

问题解决步骤

一、修复移除收藏歌曲功能

1. 统一视图与URL映射

确保你的URL配置中,likesong视图对应的URL名称和HTML表单的action一致。如果当前URL名称是music:likesong,修改HTML中的表单action:

<form id="delform" action="{% url 'music:likesong' %}" method="post">

2. 修正state字段值

在收藏列表的循环中,当前歌曲已被用户收藏,直接给state赋值为liked,确保视图能触发移除逻辑:

<input type="hidden" id="state" name="state" value="liked">

3. 替换图标为红色心形

将删除按钮的图标换成红色实心心形(符合需求),并优化按钮样式:

<button type="submit" id="submitremove" style="color: red; margin-top: 15px; background: transparent; border: none; cursor: pointer;">
    <i style="margin-left: 200px" class="fa-solid fa-heart fa-2x"></i>
</button>

4. 优化视图逻辑(可选)

用get_object_or_404替代直接get,避免歌曲不存在时抛出错误,同时简化移除判断:

from django.shortcuts import get_object_or_404

def likesong(request):
    user = request.user
    if not user.is_authenticated:
        return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
    
    if request.method == "POST":
        song_id = request.POST.get('song_id')
        state = request.POST.get('state')
        song = get_object_or_404(Song, song_id=song_id)
        
        if state == 'liked':
            song.liked_by_users.remove(user)
        else:
            song.liked_by_users.add(user)
        
        return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

二、实现所有页面已收藏歌曲显示红色心形

在任何遍历歌曲的模板中,通过Django模板语法判断当前用户是否收藏该歌曲,动态渲染心形图标:

{% for song in songs %}
    <!-- 歌曲基础信息展示 -->
    <form action="{% url 'music:likesong' %}" method="post">
        {% csrf_token %}
        <input type="hidden" name="song_id" value="{{ song.song_id }}">
        <input type="hidden" name="state" value="{% if request.user in song.liked_by_users.all %}liked{% else %}unliked{% endif %}">
        <button type="submit" style="background: transparent; border: none; cursor: pointer;">
            {% if request.user in song.liked_by_users.all %}
                <i class="fa-solid fa-heart fa-2x" style="color: red;"></i>
            {% else %}
                <i class="fa-regular fa-heart fa-2x"></i>
            {% endif %}
        </button>
    </form>
{% endfor %}

三、排查要点

  • 确认用户已登录:未登录用户无法操作收藏,可在模板中添加判断隐藏按钮或提示登录
  • 检查POST参数:用浏览器开发者工具查看Network请求,确认song_id和state是否正确传递
  • 验证CSRF令牌:每个表单必须包含{% csrf_token %},否则POST请求会被拒绝

内容的提问来源于stack exchange,提问作者Federico Monetti

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 04:22:38