Django添加点赞功能后调用post_detail提示缺少self参数如何解决
核心报错原因
你当前的post_detail是函数视图,不需要self参数,self是类视图的专属实例参数,你混用了类视图和函数视图的写法,才会触发参数缺失报错,同时还有多处逻辑、参数顺序错误,按以下步骤修改即可:
修改1:修正post_detail函数视图代码
def post_detail(request, slug): template_name = "post_detail.html" # 已通过slug查到post对象,不需要重复查询 post = get_object_or_404(Post, slug=slug) # 直接用已查询到的post计算点赞数和点赞状态 total_likes = post.total_likes() liked = False # 增加登录判断避免未登录用户访问报错,过滤条件用用户id而非slug if request.user.is_authenticated and post.likes.filter(id=request.user.id).exists(): liked = True # 初始化上下文变量,避免未定义报错 context = { "post": post, "total_likes": total_likes, "liked": liked, } comments = post.comments.filter(active=True).order_by("-created_on") new_comment = None # 评论逻辑保留 if request.method == "POST": comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.post = post new_comment.save() else: comment_form = CommentForm() # 把评论相关变量合并到上下文 context.update({ "comments": comments, "new_comment": new_comment, "comment_form": comment_form, }) # 修正render参数顺序:request → 模板路径 → 上下文 return render(request, template_name, context)
修改2:修正LikeView跳转参数不匹配问题
你当前post_detail用slug作为路由参数,跳转时需要传slug而非pk:
def LikeView(request, pk): post = get_object_or_404(Post, id=request.POST.get('post_id')) if request.user.is_authenticated: if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) else: post.likes.add(request.user) # 传slug参数匹配post_detail的路由要求 return HttpResponseRedirect(reverse('post_detail', args=[post.slug]))
可选优化
Post模型中likes字段的related_name为blog_Post,和其他命名风格不一致,建议改为小写blog_post避免后续拼写错误。
内容的提问来源于stack exchange,提问作者Dinindu Theekshana
相关产品推荐
相关产品推荐

