A template filter is used to work with and manipulate data in our templates. They can be used for a lot of things like date formatting, humanizing, transform to uppercase and similar.
In this part, I will begin by showing th date filter and after that, the naturaltime filter. But first, we need to add a date field to our tasks.
...
Class Task(models.Model):
user = models.ForeignKey(User, related_name='tasks', on_delete=models.CASCADE)
category = models.ForeignKey(Category, related_name='tasks', on_delete=models.CASCADE)
title = models.CharField(max_length=255)
description = models.TextField(blank=True, null=True)
is_done = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True) # 1, new
1. Here we added the "created_at" and set it to be a DateTimeField. This has both date and time. We use a parameter called "auto_now_add", this makes sure that when we add a task. It will be filled in automatically.
Next step then is to update the database again:
$ python3 manage.py makemigrations
And then run the migrations scripts:
$ python3 manage.py migrate
Great, next step then is the template. Open up frontpage.html:
{% extends 'task/base.html' %}
{% block content %}
<div class="frontpage">
<h1>{{ title }}</h1>
<div class="columns">
<div class="column is-8">
<h2>Tasks</h2>
..
{% for task in tasks %}
<div>
<p>{{ task.title }} - {{ task.created_at }}</p>
</div>
{% endfor %}
</div>
...
</div>
</div>
{% endblock %}
If you run this now, you will see a timestamp next to the title. Let's change it a little bit:
{{ task.created_at|date:"Y-m-d" }}
If you run this now, you will see the year-month-day. Let's add hours and minutes as well:
{{ task.created_at|date:"Y-m-d H:i" }}
So this is how you can add filters with parameters. Let's try a different one:
{{ task.created_at|naturaltime }}
If you run this now, you will see how long time it has been since the task was created.
Table of contents
- 1. Introduction
- 2. Installation and setup
- 3. How things work
- 4. The first Django app
- 5. Your first view
- 6. Your first template
- 7. Testing our site
- 8. Extending templates
- 9. Your first model
- 10. The admin interface
- 11. Showing contents from the model
- 12. Another app (category)
- 13. Connecting two models
- 14. Show list of categories
- 15. Category detail page
- 16. Separate url files and why
- 17. Adding tasks in the front end
- 18. Editing tasks
- 19. Completing and deleting tasks
- 21. Prettying up the design a little bit
- 22. Make it possible to sign up
- 23. Logging in
- 24. Logging out
- 25. Show only your data
- 26. Creating a model function
- 27. Template filters