Reputation: 6583
I'm trying to use a ListView to avoid creating a view for what should be quite a simple page. Basically I want to list a set of objects related to the current user, however I'm not sure how to access the session values from within the urls.py.
What I have looks something like this:
(r'^myrecords/$', ListView.as_view(
queryset=Record.objects.filter(CURRENT LOGGED IN USER),
context_object_name='record_list',
template_name='records.html')),
What do I need to do?
Also is there any way to apply the login_required decorator to this?
Any advice would be greatly appreciated.
Thanks.
Upvotes: 3
Views: 875
Reputation: 37227
See the docs on dynamic filtering.
You should subclass ListView
and override the get_queryset
method. When the class-based view is called, self
is populated with the current request (self.request
) as well as anything captured from the URL (self.args
, self.kwargs
).
from django.views.generic import ListView
from myapp.models import Record
class MyRecordsListView(ListView):
context_object_name = 'record_list'
template_name = 'records.html',
def get_queryset(self):
return Record.objects.filter(user=self.request.user)
There's also documentation for decorating class-based views. Basically you can just decorate the result of as_view
in your urls.py
:
(r'^myrecords/$', login_required(MyRecordsListView.as_view())),
Upvotes: 4