Question:
How to create a to-do list for users, with only incomplete tasks in Django?

Problem

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


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

properly getcontextdata doesn't accept the filter function, cause there are no tasks displayed 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`


Solution

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.


Answered by: >Willem Van Onsem

Credit: >StackOverflow


Blog Links

>Sorting the restframework in Django

>Ways to access instances of models in view in order to save both forms at once in Django

>What makes index.html have such kind of name in Django?

>Fix Module Not Found during Deployment- Django

>Creating a Django with existing directories, files, etc.?

>How to Read a CSV file with PHP using cURL?


Nisha Patel

Nisha Patel

Submit
0 Answers