赋值前引用的局部变量 'like'
local variable 'like' referenced before assignment
我在尝试加载页面时遇到以下错误:local variable 'like' referenced before assignment
。在我的上下文中,它可以追溯到 "like": like,
。
有人可以帮我解决这个问题吗?
谢谢!
views.py:
def photo_detail(request, photo_slug):
photos = Photo.objects.filter(slug=photo_slug)
obj = get_object_or_404(Photo, slug=photo_slug)
all_comments = obj.comment_set.all()
truncate_amount = 3
display_comments = obj.comment_set.all()[:int(truncate_amount)]
for c in all_comments:
c.get_children()
comment_form = CommentForm()
try:
like = Like.objects.get(pk=obj.id)
except Like.DoesNotExist:
pass
context = {
"all_comments": all_comments,
"comment_form": comment_form,
"display_comments": display_comments,
"like": like,
"obj": obj,
"photos": photos,
"truncate_amount": truncate_amount
}
return render(request, "photos/photo_detail.html", context)
如果你得到一个 Like.DoesNotExist
异常,你只是 pass
,没有分配任何东西给 like
。但是无论如何你都会尝试使用它。因此,错误告诉您您在为其分配任何内容之前尝试使用它。
如果你想分配一些 "fallback" 值,比如 None
,你可以明确地这样做:
try:
like = Like.objects.get(pk=obj.id)
except Like.DoesNotExist:
like = None
我在尝试加载页面时遇到以下错误:local variable 'like' referenced before assignment
。在我的上下文中,它可以追溯到 "like": like,
。
有人可以帮我解决这个问题吗?
谢谢!
views.py:
def photo_detail(request, photo_slug):
photos = Photo.objects.filter(slug=photo_slug)
obj = get_object_or_404(Photo, slug=photo_slug)
all_comments = obj.comment_set.all()
truncate_amount = 3
display_comments = obj.comment_set.all()[:int(truncate_amount)]
for c in all_comments:
c.get_children()
comment_form = CommentForm()
try:
like = Like.objects.get(pk=obj.id)
except Like.DoesNotExist:
pass
context = {
"all_comments": all_comments,
"comment_form": comment_form,
"display_comments": display_comments,
"like": like,
"obj": obj,
"photos": photos,
"truncate_amount": truncate_amount
}
return render(request, "photos/photo_detail.html", context)
如果你得到一个 Like.DoesNotExist
异常,你只是 pass
,没有分配任何东西给 like
。但是无论如何你都会尝试使用它。因此,错误告诉您您在为其分配任何内容之前尝试使用它。
如果你想分配一些 "fallback" 值,比如 None
,你可以明确地这样做:
try:
like = Like.objects.get(pk=obj.id)
except Like.DoesNotExist:
like = None