当我尝试加载页面时出现以下错误:local variable 'like' referenced before assignment
。它在我的上下文中追溯到"like": 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)
您应该删除行'照片= Photo.objects.filter(塞= photo_slug)'为之后你不使用“照片”。你想用'like = Like.objects.get(pk = obj.id)'来实现什么? 'obj.id'是'Photo'对象的id,你不能用它来检索'Like'对象。我想你想要做的事情就像是'Like.objects.get(photo = obj)',也许发布你的模型,以便我们可以帮助你更多。 – aumo
谢谢@aumo的输入!我将该行更改为'Like.objects.get(photo = obj)'。我保存了'photos = Photo.objects.filter(slug = photo_slug)',因为稍后在我的html模板中使用它来显示图像。 – jape
“photo_slug”不是唯一的字段吗?如果是这样,所有'照片'将永远包含一个列表包含一个单一的元素是'obj'。 – aumo