如何在ViewClass中使用请求

时间:2018-05-20 22:26:04

标签: python django django-templates

我正在使用循环django民意调查app教程 我创建了包含授权字段的问题模型,其中我存储了有权查看问题的用户的ID

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    users = User.objects.values_list('id','username')
    authorized = MultiSelectField(choices=users,null=True)
    def __str__(self):
        return "{question_text}".format(question_text=self.question_text)

我在撰写视图时遇到问题,因为idk如何使用flask import request来获取用户ID,以便只显示为登录用户设计的那些问题

class VotesView(generic.ListView):
    template_name = 'polls/votes.html'
    model = Question

    def get_queryset(request):
        return Question.objects.filter(authorized__icontains=request.user.id)

不断收到错误:

    return Question.objects.filter(authorized__icontains=request.user)
AttributeError: 'VotesView' object has no attribute 'user' 

This typically means that you attempted to use functionality that needed
an active HTTP request.  Consult the documentation on testing for
information about how to avoid this problem.

感谢您的帮助,我坚持了2天

1 个答案:

答案 0 :(得分:2)

通常在Django中,实例方法的第一个参数是self,它是对当前调用的对象的引用。所以你应该用self参数重写它。

当然,我们的self 不是请求。但好消息是:ListView具有.request属性,因此我们可以通过.request属性获取用户:

class VotesView(generic.ListView):
    template_name = 'polls/votes.html'
    model = Question

    def get_queryset(self):
        return Question.objects.filter(
            authorized__icontains=self.request.user.id
        )