我是新来的django。我想在html模板文件中经过特定的天数或周数后获取日期。
我的模板文件代码:
{% for factors in c.factor %}
{% for factor_details in factors.factor_values %}
{{factor_details.id}}
{{factor_details.factor_value}}
# here this is given date {{order_detail.oderdate}} and this is number of days and weeks {{factor_details.factor_value}}.
{% endfor %}
{% endfor %}
订购型号:
class Order(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True,on_delete=models.CASCADE)
order_no = models.CharField(max_length=120, blank=True) # AB31DE3
shipping_address = models.ForeignKey(Addresses, related_name="shipping_address",null=True, blank=True,on_delete=models.CASCADE)
billing_address = models.ForeignKey(Addresses, related_name="billing_address",null=True, blank=True,on_delete=models.CASCADE)
cart = models.ForeignKey(Cart,on_delete=models.CASCADE)
shipping_total = models.DecimalField(default=0.00, max_digits=65, decimal_places=2)
totalamount = models.DecimalField(default=0.00, max_digits=65, decimal_places=2)
stripe_id = models.CharField(max_length=120, blank=True)
payment_status = models.CharField(max_length=120, blank=True)
oderdate = models.DateTimeField(auto_now_add=True)
is_active = models.BooleanField(default=True)
因子模型:
class ProductPriceFactor(models.Model):
factor_value = models.CharField(max_length=255)
name = models.CharField(max_length=255)
is_active = models.BooleanField(default=True)
来自不同模型的 orderdate和factor_values,因此来自order
模型的orderdate和来自ProductPriceFactor
模型的factor_value。请帮我。
答案 0 :(得分:1)
我假设factor_details
来自模型。然后,您可以在模型中添加方法并在模板中呈现值。例如:
import datetime
class FactorDetail(models.Model):
...
def date_after_some_days(self):
return self.oderdate + datetime.timedelta(days=self.factor_value)
然后在模板中呈现值:
{% for factor_details in factors.factor_values %}
{{ factor_details.id }}
{{ factor_details.factor_value }}
{{ factor_details.date_after_some_days }}
{% endfor %}
以上解决方案在这里不起作用,因为您在orderdate和factor_value之间没有任何关系。相反,您可以创建一个template filter
:
# template filter tag
@register.filter(name='factor_date')
def factor_date(value, arg):
return value + datetime.timedelta(days=int(arg))
并使用过滤器更新模板:
{% for factor_details in factors.factor_values %}
{{ factor_details.id }}
{{ factor_details.factor_value }}
{{ orderdetail.oderdate|factor_date:factor_details.factor_value }}
{% endfor %}