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
相关产品推荐
相关产品推荐

