python - user.is_staff 出现属性错误

标签 python django authentication

菜鸟正在处理 official tutorial part5 testing : “也许应该允许登录的管理员用户查看未发布的问题,但普通访问者则不允许。”

这里是我的相关代码(# 后面有一些不起作用的变体):

from django.contrib.auth.models import User

class IndexView(generic.ListView):
    template_name = 'polls/index.html'
    context_object_name = 'latest_question_list'
    user = User

    #def get_queryset(self):
    def get_queryset(request):
        """Return the last five published questions."""
        #user = get_object_or_404(User, pk=user_id)
        #user = User
        if request.user.is_staff:
            return Question.objects.order_by('-pub_date')[:5]
        else:
            return Question.objects.exclude(choice__isnull=True).filter(pub_date__lte=timezone.now()
                                   ).order_by('-pub_date')[:5]

有可能做这样的事情吗? 它给出了错误:

type object 'User' has no attribute 'is_staff'

谢谢

最佳答案

在这种情况下,

request.user 是您的User 模型类,而不是模型实例。问题出在您如何定义 get_queryset() 实例方法:

def get_queryset(request):

基本上,request 不是当前请求对象 - 它取代了 self 的位置并指向 ListView 实例。然后您将获得 request.user,它是一个 User 模型类。

self.request.user获取当前用户:

class IndexView(generic.ListView):
    template_name = 'polls/index.html'
    context_object_name = 'latest_question_list'

    def get_queryset(self):
        """Return the last five published questions."""
        if self.request.user.is_staff:
            return Question.objects.order_by('-pub_date')[:5]
        else:
            return Question.objects.exclude(choice__isnull=True).filter(pub_date__lte=timezone.now()
                                   ).order_by('-pub_date')[:5]

关于python - user.is_staff 出现属性错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34455260/

相关文章:

python - 用 Pandas 分块将唯一行写入 CSV

python - 将 .format() 与大量替换字段一起使用

python - Django 中的 DRY View

python - * : 'NoneType' and 'int' in Python 3 不支持的操作数类型

python - 如何迭代一个既可以是整数又可以是数组的变量?

python - 未找到 'password_reset_done' 的反向。 'password_reset_done' 不是有效的 View 函数或模式名称

django - 有什么比 Django 的平面页面更好的吗?

java - 登录表单到 tomcat 中的安全应用程序

jsp - 如何使用带身份验证的servlet和jsp?

authentication - OAuth2 : Resource Owner OpenID Grant?