django模板中的格式编号

Oli*_*Oli 141 python django

我正在尝试格式化数字.例子:

1     => 1
12    => 12
123   => 123
1234  => 1,234
12345 => 12,345
Run Code Online (Sandbox Code Playgroud)

这是一个相当常见的事情,但我无法弄清楚我应该使用哪个过滤器.

编辑:如果你有一个通用的Python方法来做到这一点,我很高兴在我的模型中添加一个格式化的字段.

Ned*_*der 280

Django贡献的人性化应用程序执行此操作:

{% load humanize %}
{{ my_num|intcomma }}
Run Code Online (Sandbox Code Playgroud)

请务必将其添加'django.contrib.humanize'到文件中的INSTALLED_APPS列表中settings.py.

  • 有这么几个简单的过滤器不属于内置过滤器的原因吗? (16认同)
  • @PawelRoman避免加载很少使用的一堆过滤器和标签(因此使模板渲染速度更快) (8认同)
  • 人性化是内置的 - 它是django的一部分. (7认同)

Vin*_*rup 99

在其他答案的基础上,将其扩展为浮点数,您可以:

{% load humanize %}
{{ floatvalue|floatformat:2|intcomma }}
Run Code Online (Sandbox Code Playgroud)

  • Django 4.0 及更高版本允许使用“g”参数来打开分组。`{{ floatvalue|floatformat:"2g" }}` 将给出 2 位小数,并以本地化格式按“千”分组。 (2认同)

Dav*_*ith 59

关于Ned Batchelder的解决方案,这里有2个小数点和1个美元符号.这就像是my_app/templatetags/my_filters.py

from django import template
from django.contrib.humanize.templatetags.humanize import intcomma

register = template.Library()

def currency(dollars):
    dollars = round(float(dollars), 2)
    return "$%s%s" % (intcomma(int(dollars)), ("%0.2f" % dollars)[-3:])

register.filter('currency', currency)
Run Code Online (Sandbox Code Playgroud)

然后你可以

{% load my_filters %}
{{my_dollars | currency}}
Run Code Online (Sandbox Code Playgroud)

  • 以上代码上的错误,试试这个:`>>> currency(0.99958)u'$ 0.00'` (3认同)

car*_*ing 17

尝试在settings.py中添加以下行:

USE_THOUSAND_SEPARATOR = True
Run Code Online (Sandbox Code Playgroud)

这应该工作.

请参阅文档.


更新于2018-04-16:

还有一种python方式来做这件事:

>>> '{:,}'.format(1000000)
'1,000,000'
Run Code Online (Sandbox Code Playgroud)

  • 使用时请小心.还会格式化您添加到模板的网址和其他网址中的数字 (7认同)
  • 我不能强调@Christoffer的评论 - 在模板中,id被渲染并在链接中使用,这可能会引起严重的问题! (4认同)

muh*_*huk 11

如果你不想参与locales,这里有一个格式化数字的函数:

def int_format(value, decimal_points=3, seperator=u'.'):
    value = str(value)
    if len(value) <= decimal_points:
        return value
    # say here we have value = '12345' and the default params above
    parts = []
    while value:
        parts.append(value[-decimal_points:])
        value = value[:-decimal_points]
    # now we should have parts = ['345', '12']
    parts.reverse()
    # and the return value should be u'12.345'
    return seperator.join(parts)
Run Code Online (Sandbox Code Playgroud)

从此函数创建自定义模板筛选器是微不足道的.


Min*_*ark 10

人文化的解决方案是好的,如果你的网站是英文的.对于其他语言,您需要另一种解决方案:我建议使用Babel.一种解决方案是创建自定义模板标记以正确显示数字.方法如下:只需创建以下文件your_project/your_app/templatetags/sexify.py:

# -*- coding: utf-8 -*-
from django import template
from django.utils.translation import to_locale, get_language
from babel.numbers import format_number

register = template.Library()

def sexy_number(context, number, locale = None):
    if locale is None:
        locale = to_locale(get_language())
    return format_number(number, locale = locale)

register.simple_tag(takes_context=True)(sexy_number)
Run Code Online (Sandbox Code Playgroud)

然后,您可以在模板中使用此模板标记,如下所示:

{% load sexy_number from sexify %}

{% sexy_number 1234.56 %}
Run Code Online (Sandbox Code Playgroud)
  • 对于美国用户(locale en_US),这将显示1,234.56.
  • 对于法语用户(语言环境fr_FR),这将显示1 234,56.
  • ...

当然你可以改用变量:

{% sexy_number some_variable %}
Run Code Online (Sandbox Code Playgroud)

注意:context我的示例中当前未使用该参数,但我将其放在那里以表明您可以轻松调整此模板标记,以使其使用模板上下文中的任何内容.


gec*_*kos 5

基于 muhuk 的回答,我做了这个简单的标签封装 pythonstring.format方法。

  • templatetags在您的应用程序文件夹中创建一个。
  • 在其上创建一个format.py文件。
  • 将其添加到其中:

    from django import template
    
    register = template.Library()
    
    @register.filter(name='format')
    def format(value, fmt):
        return fmt.format(value)
    
    Run Code Online (Sandbox Code Playgroud)
  • 将其加载到您的模板中{% load format %}
  • 用它。{{ some_value|format:"{:0.2f}" }}