使用post.get_absolute_url时出现AttributeError错误的解决方法
解决Django博客中get_absolute_url触发的AttributeError错误
错误原因
你在Post模型的get_absolute_url方法里,错误地将**模型管理器published**当作日期字段来调用year/month/day属性。published是你定义的自定义查询管理器,只能通过模型类(如Post.published)访问,不能通过模型实例(self.published)调用,这直接导致了"Manager isn't accessible via Post instances"错误。
修复方法
修改Post模型中的get_absolute_url方法,把self.published替换为对应的日期字段self.publish:
def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug])
额外提示
你的post_detail视图当前返回的是列表模板blog/post/list.html,这通常不符合逻辑,建议替换为详情页模板(比如blog/post/detail.html),确保详情页渲染正确:
def post_detail(request, year, month, day, slug): post = get_object_or_404(Post, slug=slug, status='published', published__year=year, published__month=month, published__day=day) # 替换为详情模板 return render(request, 'blog/post/detail.html', {'post': post})
内容的提问来源于stack exchange,提问作者MMEEUR
相关产品推荐
相关产品推荐

