21๐
โ
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)
๐คpythad
6๐
@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)
๐คQuique
0๐
I would try to do that in the __init__
method:
@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)
- What is the proper way of testing throttling in DRF?
- Issue with Django 2.0 : 'WSGIRequest' object has no attribute 'session'
- Django tests complain of missing tables
- Database table names with Django
- Django 'resolve' : get the url name instead of the view_function
0๐
I think in the class-based views you would need to override the get_queryset() method in order to have access to the self.request object attached to the instance of the view rather than do this at the class level. The Classy Class-Based Views site has more information: http://ccbv.co.uk/projects/Django/1.8/django.views.generic.list/ListView/
๐คdevinformatics
- How to serialize an 'object list' in Django REST Framework
- Google.maps.event.addDomListener() is deprecated, use the standard addEventListener() method instead : Google Place autocomplete Error
- How to use the admin autocomplete field in a custom form?
Source:stackexchange.com