Reputation: 418
In Django I am trying to filter some posts based on a user. I have looked it up and found that the way to do it (or the way that was suggested), is to use request.user, but when I do this I get an error saying name 'request' is not defined
View:
class MyPost(ListView):
model = Post
template_name = "public/list.html"
paginate_by = 3
def get_context_data(self, **kwargs):
context = super(MyPost, self).get_context_data(**kwargs)
context['post'] = Post.objects.filter(live=True, user=request.user)
return context
I am unsure if this is the way to do it or not, but I couldn't find anywhere that had good documentation on this. If anyone can help that would be great.
Upvotes: 1
Views: 485
Reputation: 51998
Try like this:
def get_context_data(self, **kwargs):
context = super(MyPost, self).get_context_data(**kwargs)
context['post'] = Post.objects.filter(live=True, user=self.request.user) # used self for object reference
return context
I would also recommend to subclass your ListView from LoginRequiredMixin to ensure the view is only accessible for logged in user. You can do it like this:
from django.contrib.auth.mixins import LoginRequiredMixin
class MyPost(LoginRequiredMixin, ListView):
# rest of the code
Upvotes: 4