0

尝试加载页面时出现以下错误:local variable 'like' referenced before assignment. 它可以追溯到"like": like,我的上下文。

有人可以帮我解决这个问题吗?

谢谢!

视图.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)
4

1 回答 1

1

如果你得到一个Like.DoesNotExist例外,你只是pass,没有分配任何东西给like. 但是你无论如何都要尝试使用它。因此,错误告诉您在分配任何内容之前您尝试使用它。

如果你想分配一些“后备”值,比如None,你可以明确地做到这一点:

try: 
    like = Like.objects.get(pk=obj.id)
except Like.DoesNotExist:
    like = None
于 2015-05-01T23:09:57.743 回答