如何在基于类的视图中获取用户的ID?
这是我的CBW
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_question_list'
context = 'activate'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['activate'] = 'Polls'
return context
def get_queryset(self):
"""Return the last five published questions."""
return Question.objects.exclude(panel__user='???',
panel__valid=False)
.order_by('-pub_date')[:5]
答案 0 :(得分:6)
使用self.request.user
:
def get_queryset(self):
"""Return the last five published questions."""
return Question.objects.exclude(panel__user=self.request.user,
panel__valid=False)
.order_by('-pub_date')[:5]
答案 1 :(得分:4)
在Django ClassBasedViews中,您可以将用户的ID获取为
Data Source=XXXX;Proxy User Id=PROXY;Proxy Password=PROXYPASS;User Id=MYDOMAIN\MYUSER;
答案 2 :(得分:3)
您应该使用self.request.user.pk
来获取登录用户ID。要确保用户已登录,请同时使用loginrequiredmixin
。
from django.contrib.auth.mixins import LoginRequiredMixin
class IndexView(LoginRequiredMixin, generic.ListView):
template_name = 'polls/index.html'
login_url = '/login/'
redirect_field_name = 'redirect_to'
context_object_name = 'latest_question_list'
context = 'activate'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
login_user_id = self.request.user.pk
context['activate'] = 'Polls'
return context