如何在ViewClass中使用请求

问题描述 投票:-1回答:1

我正在工作回收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天

python django django-templates
1个回答
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
        )
© www.soinside.com 2019 - 2024. All rights reserved.