djangopython-3.xdjango-class-based-viewsdjango-1.8django-generic-views

django filtering by user id in Class based ListView


I have a class based ListView of which I would like to filter the objects by the logged in user_id since Item model has a foreign key to settings.AUTH_USER_MODEL

class ItemListView(LoginRequiredMixin, StaffRequiredMixin, ListView):
  model = Item
  template_name = "items/list_items.html"

In function based views I can do this using request.user but not in generic Class based views. Any ideas of how to best do this?

Here is the Item model

class Item(models.Model):
  user = models.ForeignKey(settings.AUTH_USER_MODEL)
  description = models.CharField(max_length=300)

Solution

  • You can override get_queryset function in ListView and filter on self.request.user

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