vij*_*ker 8 python django django-templates
我正在循环推车项目,并希望将数量乘以单位价格,如下所示:
{% for cart_item in cart.cartitem_set.all %}
{{cart_item.quantity}}*{{cart_item.unit_price}}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
有可能做那样的事吗?任何其他方式!谢谢
Bra*_*don 14
您需要使用自定义模板标记.模板过滤器只接受单个参数,而自定义模板标记可以接受所需数量的参数,进行乘法并将值返回到上下文.
您需要查看Django 模板标签文档,但一个简单的例子是:
from django import template
register = template.Library()
@register.simple_tag()
def multiply(qty, unit_price, *args, **kwargs):
# you would need to do any localization of the result here
return qty * unit_price
Run Code Online (Sandbox Code Playgroud)
你可以这样打电话:
{% load your_custom_template_tags %}
{% for cart_item in cart.cartitem_set.all %}
{% multiply cart_item.quantity cart_item.unit_price %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
您确定不想将此结果作为购物车项目的属性吗?当您结账时,您似乎需要将此信息作为购物车的一部分.
小智 8
或者您可以在模型上设置属性:
class CartItem(models.Model):
cart = models.ForeignKey(Cart)
item = models.ForeignKey(Supplier)
quantity = models.IntegerField(default=0)
@property
def total_cost(self):
return self.quantity * self.item.retail_price
def __unicode__(self):
return self.item.product_name
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
18921 次 |
最近记录: |