Change color of a field in a table depending on how much time is left for the user to pay with Django
I am trying to change the color of a field in a table depending on how much time is left for the user to pay, if there are 7 days to pay it should change to yellow and if it is already the date of payment or already had to have paid it should change to red, the one that changes to red I got it, but I can't get it to change to yellow when there are 7 days to pay.
This is my model and the def
class payments (models.Model):
client = models.OneToOneField(HealthQuests, on_delete=models.CASCADE, null=True, blank=True, verbose_name= 'Cliente')
date = models.DateField(default=datetime.date.today, verbose_name= 'Fecha de facturación')
payment_date = models.DateField(default=datetime.date.today, verbose_name= 'Fecha de pago')
amount = models.FloatField(verbose_name='Monto de pago', default=0)
def payment_yellow (self):
return date.today() - payments.payment_date
def payment_red (self):
return date.today()
And my html and the if
<tbody>
{% for obj in object_list %}
<tr>
<td><a href="update_payments/{{ obj.id }}" class="btn">{{ obj.client }}</a></td>
<td>{{ obj.date }}</td>
<td>
{% if obj.payment_date <= obj.payment_red %}
<div class="p-3 mb-2 bg-danger text-white">{{ obj.payment_date }}</div>
{% elif obj.payment_yellow >= 7 %}
<div class="p-3 mb-2 bg-warning text-white">{{ obj.payment_date }}</div>
{% else %}
{{ obj.payment_date }}
{% endif %}
</td>
<td>{{ obj.amount }}</td>
</tr>
{% endfor %}
</tbody>
It is because you hardcoded the condition check to 7
in the template, the function returns timedelta
between current date and the payment date.
Also, it should be self.payment_date
not payments.payment_date
.
So currently you should extract days to make your code work in payment_yellow()
method so:
def payment_yellow(self):
return (self.payment_date - date.today()).days
Note: Django models are generally written in
PascalCase
and don't requires
to be added as suffix, as it is by default added, so it is better to name it asPayment
not.payments