How to access current user in Django class based view
@pythad's answer is correct. But on Django 1.9+, instead of the dispatch
method, you can use django.contrib.auth.mixins.LoginRequiredMixin to replace the old-style @login_required decorator.
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)
You can just overwrite 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)
Also you can't use decorators on classes, so you have to write something like this:
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)