Django处理状态检查中的匿名用户

时间:2019-05-04 17:58:37

标签: python django

我想让此功能与AnonymousUser一起使用,但不知道在状态行中谁应该为AnonymousUser正确过滤:

def post_sell_multiple_detail(request, pk):
    post = get_object_or_404(Post_Sell_Multiple, pk=pk)
    list_comments = Post_Sell_Multiple_Comment.objects.get_queryset().filter(post_id=pk).order_by('-pk')
    status = Post_Paid_Sell_Multiple.objects.filter(user=request.user, post_id=pk, status=1).count()
    paginator = Paginator(list_comments, 10)
    page = request.GET.get('commentpage')
    comments = paginator.get_page(page)
    return render(request, 'app/Post_Sell_Multiple/post_sell_multiple_detail.html',
                  {'post': post,
                   'comments': comments,
                   'status': status
                   })

我用一个用户创建了它的正常工作,但是没有使用AnonymousUser。目前,我在这里收到以下错误:

  / p / 1 / sell_multiple中的

TypeError

     

'AnonymousUser'对象不是    可迭代的

亲切的问候

1 个答案:

答案 0 :(得分:1)

您可以使用user.is_authenticated来检查用户是否登录,并根据该信息进行过滤:

post = get_object_or_404(Post_Sell_Multiple, pk=pk)
list_comments = Post_Sell_Multiple_Comment.objects.get_queryset().filter(post_id=pk).order_by('-pk')
if request.user.is_authenticated:
     status = Post_Paid_Sell_Multiple.objects.filter(user=request.user, post_id=pk, status=1).count()
else:
     status =  Post_Paid_Sell_Multiple.objects.filter(post_id=pk, status=1).count()
paginator = Paginator(list_comments, 10)
page = request.GET.get('commentpage')
comments = paginator.get_page(page)
return render(request, 'app/Post_Sell_Multiple/post_sell_multiple_detail.html',
                  {'post': post,
                   'comments': comments,
                   'status': status
                   })