在赋值之前引用/ local变量'user'的UnboundLocalError

时间:2016-01-14 00:39:34

标签: python django

我正在使用django-favorite,https://bitbucket.org/last_partizan/django-favorites并尝试显示“仅获取用户的博客收藏”策略以获取我的收藏。在文档中,它说

content_type = get_object_or_404(ContentType, app_label='myblogapp', model='blogpost')
favs = Favorite.objects.favorites_for_user(user).filter(content_type=content_type)

将完成这项工作。所以在我的views.py中我添加了

def index(request):
        user = MyProfile.objects.get(username=user)

        categories = Category.objects.all()
        try:
                sort = request.GET["sort"].strip()
                sort_method = SortMethods[sort]
                page = request.GET["page"].strip()
        except KeyError:
                sort_method = SortMethods.score
                page = 1

        if sort_method == SortMethods.date:
                post_list = Post.objects.order_by("-pub_date")
        else:
                post_list = Post.objects.all()
                post_list = sorted(post_list, key=lambda x: x.get_score(), reverse=True)

        paginator = Paginator(post_list, 30)

        try:
                posts = paginator.page(page)
        except PageNotAnInteger:
                posts = paginator.page(1)
        except EmptyPage:
                posts = paginator.page(paginator.num_pages)

        content_type = get_object_or_404(ContentType, app_label='main', model='post')
        favs = Favorite.objects.favorites_for_user(user).filter(content_type=content_type)
        context = {
                "posts": posts,
                "pages": paginator.page_range,
                "sort": sort_method.name,
                "categories":categories,
                "favs":favs,

        }
        return render(request, "main/index.html", context)

并且在我的index.html中使用该fav,我只是放了{{fav}},我甚至不确定这是调用收藏夹的正确方法。但我试过,现在它在/

给了我UnboundLocalError

在赋值之前引用的局部变量'user'来自`user = MyProfile.objects.get(username = user)

`我有userena app,在userena模型中

  class MyProfile(UserenaBaseProfile):
    user = models.OneToOneField(User,
                                unique=True,
                                verbose_name=_('user'),
                                related_name='my_profile')
    intro = models.CharField(_('intro'),
                                       max_length=5, default="Hello")

我从这里打电话给用户......我希望这是对的。

1 个答案:

答案 0 :(得分:0)

第一行应该使用:

request.user

所以这样:

user = MyProfile.objects.get(username=request.user)