python - UnboundLocalError at / local variable 'Profile' 在赋值之前引用
问题描述
我正在写一个 django 视图,如图所示:-
def feed(request):
if request.user.is_authenticated:
user=request.user
profile=Profile.objects.filter(user=user)
userfollowing=FollowingProfiles.objects.filter(Profile=profile)
for following in userfollowing:
username=following.ProfileName
useraccount=User.objects.filter(username=username)
Profile=Profile.objects.filter(user=useraccount)
Post=post.objects.filter(Profile=Profile)
comment=comment.objects.filter(post=Post)
final_post_queryset=final_post_queryset+Post
final_comment_queryset=final_comment_queryset+comment
return render(request,'feed/feed.html',{'final_comment_queryset':final_comment_queryset,'final_post_queryset':final_post_queryset})
else:
redirect('signup')
而模板 feed.html 是:-
{% extends 'base.html' %}
{% block content %}
{% load static %}
{% for p in final_post_queryset %}
{{ p.DatePosted }}
<img src="{{ p.Picture.url }}"/>
{% endblock %}
所以错误在第三行
profile=Profile.objects.filter(user=user)
解决方案
我假设你已经导入了Profile
模块(withfrom .models import Profile
或类似的),并且对它为什么不存在感到困惑(如果你没有,你需要将该导入添加到文件的顶部)。
即使您已导入它,此代码也不起作用。您的问题是您在函数范围内分配了名称Profile
,使其成为局部变量,并且局部变量从函数的开头是局部的(但最初为空)。在将它们分配给它们之前尝试访问它们会引发UnboundLocalError
您所看到的(仅当您在分配给它之前尝试从本地名称读取时才会引发该错误;它不能仅仅通过导入失败而引发一个模块,它只会引发一个NameError
)。Profile
即使您确实导入了全局导入,也看不到它,因为在函数中,Profile
必须是本地或全局的,不能同时是两者。
要解决此问题,请为您的局部变量选择一个不同的名称,以便全局Profile
保持可访问性:
def feed(request):
if request.user.is_authenticated:
user=request.user
profile=Profile.objects.filter(user=user) # This line is fine!
userfollowing=FollowingProfiles.objects.filter(Profile=profile)
for following in userfollowing:
username=following.ProfileName
useraccount=User.objects.filter(username=username)
# Use lowercase profile, not Profile
# Profile=Profile.objects.filter(user=useraccount) # This line was the problem!
profile = Profile.objects.filter(user=useraccount) # This line is the solution!
Post = post.objects.filter(Profile=profile) # Change to match new name
... rest of your code ...
你之前已经profile
正确地使用了小写字母,而且似乎再也不需要它了,所以我只是重用了这个名字。
推荐阅读
- flutter - 如何在颤动 24 小时后删除 SharedPreferences?
- css - 用于响应式设计的 CSS 媒体查询
- php - 使用imagick创建多页pdf
- php - 设置安装 Sylius 的 Symfony 项目会出错
- javascript - Chrome 浏览器桌面通知
- mysql - 如何使用 JSON 字段连接 MySQL 表?
- angular - 如何将初始值设置为 Angular Material mat-select multiple
- c# - 禁用窗口上的 WPF 事件
- ios - iOS 应用未与动态链接 URL 前缀关联
- css - 如何跨越到隐式网格中的最后一列?