Python 如何在ViewClass内部使用请求
我在工作循环django民意测验应用程序教程 我创建了一个问题模型,其中包含authorized字段,我在其中存储有权查看问题的用户的idPython 如何在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','
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
)
Wellget\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
)