UserError与user.is_staff

时间:2015-12-24 16:05:30

标签: python django authentication

Noob正在处理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'

谢谢

1 个答案:

答案 0 :(得分:3)

在这种情况下,

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]