Template filters - 30 days of Django

Template filters - 30 days of Django

/ #Django


Let's learn what a template filter is and how to use one.

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

Comments

No comments yet...

Add comment

Newsletter

Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.