Django项目打开页面报错:'function' object has no attribute 'owner'
解决Web应用中"'function' object has no attribute 'owner'"错误
当尝试打开Web应用页面时,抛出错误:'function' object has no attribute 'owner'。
相关代码片段
@login_required def topic(request, topic_id): topic = Topic.objects.get(id=topic_id) _check_topic_owner(request) entries = topic.entry_set.order_by('-date_added') context = {'topic': topic, "entries": entries} return render(request, 'learning_logs/topic.html', context) def _check_topic_owner(request): if topic.owner != request.user: raise Http404
错误原因
核心问题是变量作用域不匹配:
- 在
topic视图函数内查询得到的topic(Topic数据库实例)属于局部变量,无法被外部的_check_topic_owner函数直接访问。 _check_topic_owner函数中引用的topic,实际指向的是同名的视图函数topic(函数本身是一个对象),而非数据库实例,因此会触发“函数对象无owner属性”的错误。
解决方案
将查询到的Topic实例作为参数传递给_check_topic_owner函数,修改后的代码如下:
1. 调整权限校验函数的参数
def _check_topic_owner(request, topic): if topic.owner != request.user: raise Http404
2. 修改视图函数的调用逻辑
@login_required def topic(request, topic_id): topic = Topic.objects.get(id=topic_id) _check_topic_owner(request, topic) # 传入Topic实例 entries = topic.entry_set.order_by('-date_added') context = {'topic': topic, "entries": entries} return render(request, 'learning_logs/topic.html', context)
修改后,_check_topic_owner函数能正确获取到Topic实例的owner属性,完成用户权限校验,错误即可解决。
内容的提问来源于stack exchange,提问作者Zeratulez
相关产品推荐
相关产品推荐

