You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django购物项目实现商品价格千位分隔(无需JavaScript)

Django实现商品价格千分位格式化(无需JavaScript)

下面提供几种无需JavaScript的后端/模板层实现方案,按需选择:

方案1:使用Django内置intcomma过滤器

Django的humanize模块自带千分位格式化过滤器,步骤如下:

  1. 在项目settings.py的INSTALLED_APPS中添加django.contrib.humanize
  2. 在需要格式化价格的HTML模板顶部加载标签库:
    {% load humanize %}
    
  3. 遍历商品时使用过滤器格式化价格:
    {% for product in products %}
        <p>{{ product.price|intcomma }} $</p>
    {% endfor %}
    

注意:如果价格是Decimal或浮点类型,intcomma同样适用;若需保留小数,可搭配floatformat过滤器,比如{{ product.price|floatformat:2|intcomma }} $

方案2:自定义模板过滤器

如果需要更个性化的格式化逻辑,可自定义过滤器:

  1. 在你的Django应用下创建templatetags目录,同时添加空的__init__.py文件(让Python识别为包)
  2. 在templatetags下新建price_filters.py,编写过滤器代码:
    from django import template
    
    register = template.Library()
    
    @register.filter
    def format_price(value):
        # 针对整数或Decimal类型格式化,保留千分位
        return "{:,}".format(value)
    
  3. 在模板中加载自定义标签库并使用:
    {% load price_filters %}
    {% for product in products %}
        <p>{{ product.price|format_price }} $</p>
    {% endfor %}
    

方案3:在模型中定义格式化属性

直接在Product模型中添加一个只读属性,提前处理价格格式:

from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=100)
    price = models.DecimalField(max_digits=10, decimal_places=2)

    @property
    def formatted_price(self):
        # 格式化价格为带千分位的字符串
        return "{:,}".format(self.price)

模板中直接调用该属性:

{% for product in products %}
    <p>{{ product.formatted_price }} $</p>
{% endfor %}

方案4:在视图中预处理价格

如果需要在视图层统一处理,可在查询后为每个商品添加格式化后的价格字段:

from django.shortcuts import render
from .models import Product

def product_list(request):
    products = Product.objects.all()
    # 为每个商品添加格式化价格
    for product in products:
        product.formatted_price = "{:,}".format(product.price)
    return render(request, 'product_list.html', {'products': products})

模板中直接使用预处理后的字段:

{% for product in products %}
    <p>{{ product.formatted_price }} $</p>
{% endfor %}

内容的提问来源于stack exchange,提问作者MrRobot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 06:47:44