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

Django实现的点赞系统点击按钮后报错该如何排查?

问题原因

总共存在4个直接导致功能失效的错误:

  • 视图函数作用域错误:ImagePostLike是函数视图,不存在self对象,重定向时调用self.id、self.slug会直接触发变量未定义报错。
  • 表单提交方式错误:模板里的点赞表单没有指定method="post",默认发送GET请求,request.POST为空,无法获取提交的参数。
  • slug参数缺失错误:表单仅提交了image_id字段,没有提交image_slug字段,get_object_or_404查询时slug参数为None,无法匹配到对应图片,触发404错误。
  • 路由命名空间错误:重定向调用reverse('image_detail')时没有加app的命名空间,无法正确解析到详情页路由。
修复方案

1. 修改模板中的表单代码

给表单添加post提交方式即可,后续可以直接复用路由传入的参数,不需要额外加隐藏字段:

{% extends 'base.html' %}
{% load thumbnail %}
{% block title %}{{image.title}}{% endblock title %}
{% block content %}
<h1>{{ image.title }}</h1>
<img src="{{ image.url }}" class="image-detail">

{% if user.is_authenticated %}
<!-- 仅修改form这一行,添加method="post"即可 -->
<form action="{% url 'images:image_like' image.id image.slug%}" method="post">
{% csrf_token %}
{% if post_is_liked %}

<button type="submit" name="image_id" value="{{image.id}}" class="btn btn-info">Unlike</button>

{% else %}
<button type="submit" name="image_id" value="{{image.id}}" class="btn btn-info">Like</button>
{% endif %}
</form>
{% else %}
 <a class="btn btn-outline-info" href="{% url 'login' %}?next={{request.path}}">>Log in to like this article!</a><br>
{% endif %}
<strong class="text-secondary">{{ number_of_likes }}  Like</strong>
{% endblock content %}

2. 修改ImagePostLike视图函数代码

直接复用路由传入的id、slug参数,删除错误的self调用,补全路由命名空间:

def ImagePostLike(request,id,slug):
    # 直接用路由传入的参数查询,不需要从POST中取值
    image=get_object_or_404(Image, id=id, slug=slug)
    if image.users_like.filter(id=request.user.id).exists():
        image.users_like.remove(request.user)
    else:
        image.users_like.add(request.user)
    # 用传入的参数和正确的命名空间生成重定向地址
    return HttpResponseRedirect(reverse('images:image_detail', args=[id, slug]))

(可选)修复模型层小问题

模型的get_absolute_url方法中路由名和urls定义不一致,修正后方便后续其他功能调用:

def get_absolute_url(self):
   return reverse('images:image_detail', args=[self.id, self.slug])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 10:39:04