[Django]-Django display specific text if date is older than 10 days

2👍

You could simply add a method to your model, like that:

class Member(models.Model):
    name = models.CharField('Name', max_length=50,)
    join_date = models.DateField('Join Date', auto_now=False, auto_now_add=False,)

    def older_than_ten_days(self):
        return (datetime.date.today() - self.join_date).days > 10

Then your template simply become:

    <tr>
        <td>{{ member.name }}</td>
        <td>{{ member.join_date }}</td>
        <td>{{ member.older_than_ten_days }}</td>
    </tr>

However, if you need to pass more parameters to the method, like a variable number of days, you have to use the Aleksander Zień solution

3👍

There are at least two ways you can achieve that

Method-lookup approach

edit: Credits for this one goes to olinox14, I didn’t see his answer while editting mine.

First, make sure you understand what is written in official documentation about Accessing method calls from within templates.

What you will find the most interesting for your cause there is:

(…) And of course you can easily access methods you’ve explicitly defined on your own models

Keeping that in mind, I encourage you to check olinox14’s answer.

Custom template tag approach

You can use Django templates’ if statement and use custom template tag to calculate actual result. It should look something like

from django import template
import datetime 


register = template.Library() 


@register.filter(expects_localtime=True)
def is_older_than_ten_days(value):
    if isinstance(value, datetime.datetime):
        value = value.date()
    delta = value - datetime.date.today()
    return delta.days > 10

And then in your template use it like this:

(...)
        {% for member in object_list %}
        <tr>
            <td>{{ member.name }}</td>
            <td>{{ member.join_date }}</td>
            <td>{% if member.join_date|is_older_than_ten_days %}YOUR INFO
                {% else %}something else{% endif %}</td>
        </tr>
        {% endfor %}
(...)

Please refer to this answer for more details.

0👍

You can get all objects and then add a field to each object whether that is 10 days old or not.You can assign a boolean variable lets say isOld and render in template by {% if isOld %} like this:

import datetime
def memberList(request, template_name='members/memberList.html'):
    data={}
    members = Member.objects.all()
    for i in members:

        delta=datetime.datetime.today() - i.join_date
        if delta.days < 10:
           i.isOld=False
        else:
           i.isOld=True
    data["object_list"]=members
    return render(request, template_name, data)

In your template you can:

{% extends "base.html" %}
{% load static %}
{% block content %}
<table>
    <thead>
    <tr>
        <th>Name</th>
        <th>Join Date</th>
        <th>Alert</th>
    </tr>
</thead>
<tbody>
    {% for member in object_list %}
    <tr>
        <td>{{ member.name }}</td>
        <td>{{ member.join_date }}</td>
        {% if member.isOld %}
        <td style="color:red;"> Old Alert</td>
        {% else %}
        <td style="color:green;"> New Alert</td>
        {% endif %}
    </tr>
    {% endfor %}
</tbody>
</table>
{% endblock %}

0👍

You can use Models.object.filter for filtering out in views.py

Like see what I have done in my project is used HTML default date for date picking i.e. proj1/templates/tasks.html

<form method="POST" action="/tasks/">
      {% csrf_token %}
      <input type="date" value="date" id="date" name="date">
      <button type="submit" class="btn-submit">Submit</button>
</form>

then in proj1/app1/models.py

class Tasks01(models.Model):
registerdb4 = models.ForeignKey(Register, on_delete=models.CASCADE)
Ename = models.CharField(u'Name of employee', max_length=100)
supervisor_name = models.CharField(u'Supervisor Name', max_length=100, blank=True)
title = models.CharField(u'Title', max_length=200)
description = models.TextField(u'Description')
day = models.DateField(u'Date')
start_time = models.TimeField(u'Starting Time')
end_time = models.TimeField(u'Ending Time')

def __str__(self):
    return "%s %s" %(self.Ename, self.day)

then in proj1/app1/views.py

def tasks(request):
if request.method == "POST":
    date01 = request.POST['date']
    s1 = request.session['session_id']
    if Tasks01.objects.filter(day=date01).exists():
        print('yes')
        task = Tasks01.objects.filter(day=date01,registerdb4=s1)
        return render(request, "tasks.html", {'task': task})
    else:
        print("no records")
        return render(request, "tasks.html")
return render(request, "tasks.html")

Leave a comment