英文:
Change color of a field in a table depending on how much time is left for the user to pay with Django
问题
def payment_yellow(self):
return date.today() - self.payment_date
def payment_red(self):
return date.today()
{% 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.days >= 7 %}
<div class="p-3 mb-2 bg-warning text-white">{{ obj.payment_date }}</div>
{% else %}
{{ obj.payment_date }}
{% endif %}
英文:
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>
答案1
得分: 1
因为您在模板中硬编码了条件检查为 7
,所以函数返回当前日期与付款日期之间的时间间隔 timedelta
。
另外,应该是 self.payment_date
而不是 payments.payment_date
。
所以目前您应该提取天数来使您的代码在 payment_yellow()
方法中工作,如下所示:
def payment_yellow(self):
return (self.payment_date - date.today()).days
注意: Django 模型通常以
PascalCase
编写,不需要添加s
作为后缀,因为默认会添加,所以最好将其命名为Payment
,而不是<s>payments</s>
。
英文:
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 require s
to be added as suffix, as it is by default added, so it is better to name it as Payment
not <s>payments
</s>.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论