TypeError at / 'AnonymousUser' object is not iterable

7 篇文章 0 订阅
4 篇文章 0 订阅

在使用filter的时候,出现了如下错误(python版本3.7.4,django 版本2.2.6):

错误显示在‘/’目录下,也就是默认的index视图下,其中index 视图的源码如下:

def index(request):
        posts=Post.objects.filter(owner=request.user).order_by('date_added')
        context={'posts':posts}
        return render(request,'blogs/index.html',context)

其中第一行filter(owner=request.user)函数需要用户登录后才能使用,但此代码下没有显示登录信息,所以显示此错误,简单来说就是在没有对用户认证前使用了需要用户认证的函数。解决方法如下:

(1)使用django提供的login_required,即添加:from django.contrib.auth.decorators import login_required,然后在index试图前加上:@login_required,表示此视图需要用户登录才能访问

(2)使用is_authenticated在认证用户之前进行验证(注意,此django 版本后面不需要'()'),修改后,源码如下:

def index(request):
    if  request.user.is_authenticated:
        posts=Post.objects.filter(owner=request.user).order_by('date_added')
        context={'posts':posts}
        return render(request,'blogs/index.html',context)
    else :
        posts=Post.objects.order_by('date_added')
        context={'posts':posts}
        return render(request,'blogs/index.html',context)

实现所需功能,即登录前显示所有用户的post,登录后只显示当前用户拥有的post

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值