Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在ViewClass内部使用请求_Python_Django_Django Templates - Fatal编程技术网

Python 如何在ViewClass内部使用请求

Python 如何在ViewClass内部使用请求,python,django,django-templates,Python,Django,Django Templates,我在工作循环django民意测验应用程序教程 我创建了一个问题模型,其中包含authorized字段,我在其中存储有权查看问题的用户的id class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') users = User.objects.values_list('id','

我在工作循环django民意测验应用程序教程 我创建了一个问题模型,其中包含authorized字段,我在其中存储有权查看问题的用户的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' 


感谢您的帮助,我在Django中花了2天的时间

通常情况下,实例方法的第一个参数是
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
        )
class VoteView(generic.ListView):
模板名称='polls/votes.html'
模型=问题
def get_queryset(自我):
返回Question.objects.filter(
授权的\uuu icontains=self.request.user.id

)
Well
get\u queryset
只有一个参数:
self
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
        )