I have a simple todolist app where each task has a Booleanfield called is_deleted. in my list template, I only want to show the tasks with is_deleted=False .
I know I can use Task.objects.all().filter(is_deleted=False) in my view; but I want to do it with managers in my template. here is my manager:
class TaskManager(models.Manager):
def available(self):
return self.filter(is_deleted=False)
.
.
objects = TaskManager()
here is my view:
class TaskList(ListView):
model = models.Task
context_object_name="tasks"
template_name = "home/list.html"
paginate_by=5
and here is the the condition in my template:
{% if tasks.available%} ...
My answer is a complement / a correction of your work :
Your manager is ok
But you need to specify in the Task model that you override the default manager by the your custom manager like this :
Class Task(models.Model):
# others fields here
# override the default objects manager
objects = TaskManager()
# You can also define a new manager and keep the default objects, in the case you will use it later.
# objects = models.Manager() -> Task.objects.all() give all objects
# is_available = TaskManager() -> Task.is_available.all() give only nt deleted task.
in your views.py
class TaskList(ListView):
model = models.Task
context_object_name="tasks"
template_name = "home/list.html"
paginate_by=5
# If you override the default objects manager with TaskManager
# Then you are nothing to do, {{ tasks }} is the queryset in the template
# If you defined two managers as recommended above, then you need
# to override the queryset attribute of the ListView
queryset = Task.is_available.all() # Explicit call of custom manager
Anyways in your template, you don't need {% if %} tag to filter results, all your task are available on the context_object_name value name.
{% for task in tasks %}
{{ task.name }}
...
{% endfor %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With