TaskList View in Django

51 Views Asked by At

I've been trying to make to do list app,

I'm trying to make for each user their own to do list, with only tasks that they didn't complate,

properly getcontextdata doesn't eccepts filter function,cause there is no tasks displayes on the template

 `
class TaskList(LoginRequiredMixin, ListView):
    model = Task
    context_object_name = "tasks"
    def get_context_data(self, **kwargs):
        context = super(TaskList, self).get_context_data(**kwargs)
        context["tasks"] = context["tasks"].filter(user=self.request.user)
        context["count"] = context["tasks"].filter(complete=False).count()
        return context`
1

There are 1 best solutions below

3
willeM_ Van Onsem On

Just filter with .get_queryset() [Django-doc]:

class TaskList(LoginRequiredMixin, ListView):
    model = Task
    context_object_name = 'tasks'

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

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['count'] = self.object_list.filter(complete=False).count()
        return context

you might also want to filter on complete=False in get_queryset.


Note: Since PEP-3135 [pep], you don't need to call super(…) with parameters if the first parameter is the class in which you define the method, and the second is the first parameter (usually self) of the function.