當我嘗試加載頁面時出現以下錯誤: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