如何在基于Django类的视图中访问当前用户

时间:2015-11-19 16:29:07

标签: python django

我无法在基于Django类的视图中访问当前登录的用户:

models.py:

class Userproject(models.Model):
class Meta:
    verbose_name = u'pp'
    verbose_name_plural = u'pps'

user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="project", verbose_name=_("Владелец проекта"))
#user = models.ForeignKey(User, unique=True)

name = models.TextField(u'Название проекта', unique=True)
date_created = models.DateTimeField(u'Дата создания', default=datetime.now(), db_index=True)
date_until = models.DateTimeField(u'Оплачен по', default=datetime.now(), db_index=True)

views.py:

@login_required
class UserprojectList(ListView):
    context_object_name = 'userproject_list'
    queryset = Userproject.objects.filter(user=self.request.user)
    template_name = 'userproject_list.html'  

当我导航到url时,我看到错误: 姓名' self'未定义

如果我将self.request.user更改为request.user 错误是:名称'请求'未定义

请注意,没有用户过滤视图正在运行并显示数据 django 1.8.5

4 个答案:

答案 0 :(得分:8)

您可以覆盖get_queryset

@login_required
class UserprojectList(ListView):
    context_object_name = 'userproject_list'
    template_name = 'userproject_list.html'
    def get_queryset(self):
        return Userproject.objects.filter(user=self.request.user)

同样你不能在类上使用装饰器,所以你必须写这样的东西:

from django.utils.decorators import method_decorator

class UserprojectList(ListView):
    context_object_name = 'userproject_list'
    template_name = 'userproject_list.html'

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(UserprojectList, self).dispatch(*args, **kwargs)

    def get_queryset(self):
        return Userproject.objects.filter(user=self.request.user)

答案 1 :(得分:0)

我会尝试在__init__方法中执行此操作:

@login_required
class UserprojectList(ListView):
    context_object_name = 'userproject_list'
    template_name = 'userproject_list.html'
    def __init__(self, *args, **kwargs):
        super(UserprojectList, self).__init__(*args, **kwargs)
        self.queryset = Userproject.objects.filter(user=self.request.user)

答案 2 :(得分:0)

我认为在基于类的视图中,您需要覆盖get_queryset()方法,以便能够访问附加到视图实例的self.request对象,而不是在类级别执行此操作。 Classy Class-Based Views网站提供了更多信息:http://ccbv.co.uk/projects/Django/1.8/django.views.generic.list/ListView/

答案 3 :(得分:0)

@pythad的答案是正确的。但是在Django 1.9+上,您可以使用django.contrib.auth.mixins.LoginRequiredMixin代替旧的@login_required装饰器,而不是dispatch方法。

from django.contrib.auth.mixins import LoginRequiredMixin

class UserprojectList(LoginRequiredMixin, ListView):
    context_object_name = 'userproject_list'
    template_name = 'userproject_list.html'

    def get_queryset(self):
        return Userproject.objects.filter(user=self.request.user)