IT

장고 템플릿의 숫자 형식

lottoking 2020. 6. 21. 19:15
반응형

장고 템플릿의 숫자 형식


숫자 형식을 지정하려고합니다. 예 :

1     => 1
12    => 12
123   => 123
1234  => 1,234
12345 => 12,345

그것은 매우 일반적인 일이지만, 어떤 필터를 사용 해야하는지 알 수 없습니다.

편집 :이 작업을 수행하는 일반적인 파이썬 방법이 있다면 모델에 서식이 지정된 필드를 추가하는 것이 좋습니다.


Django의 기여 인간화 응용 프로그램은 다음을 수행합니다.

{% load humanize %}
{{ my_num|intcomma }}

추가해야 'django.contrib.humanize'당신에 INSTALLED_APPS에 목록 settings.py파일.


다른 답변을 바탕으로 이것을 수레로 확장하려면 다음을 수행하십시오.

{% load humanize %}
{{ floatvalue|floatformat:2|intcomma }}

Ned Batchelder의 솔루션에 관해서는 여기에 소수점 2 개와 달러 기호가 있습니다. 이것은 어딘가에 간다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)

그럼 당신은 할 수 있습니다

{% load my_filters %}
{{my_dollars | currency}}

settings.py에 다음 줄을 추가하십시오.

USE_THOUSAND_SEPARATOR = True

이 작동합니다.

설명서를 참조하십시오 .


2018-04-16에 업데이트 :

이 작업을 수행하는 Python 방법도 있습니다.

>>> '{:,}'.format(1000000)
'1,000,000'

로케일에 관여하지 않으려는 경우 숫자 형식을 지정하는 함수가 있습니다.

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)

이 함수에서 사용자 정의 템플릿 필터만드는 것은 간단합니다.


인간화의 웹 사이트가 영어 인 경우 솔루션은 괜찮습니다. 다른 언어의 경우 다른 솔루션이 필요합니다 . 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)

그런 다음 템플릿에서이 템플릿 태그를 다음과 같이 사용할 수 있습니다.

{% load sexy_number from sexify %}

{% sexy_number 1234.56 %}
  • 미국 사용자 (로케일 en_US)의 경우 1,234.56이 표시됩니다.
  • 프랑스어 사용자 (로케일 fr_FR)의 경우 1 234,56이 표시됩니다.
  • ...

물론 변수를 대신 사용할 수 있습니다.

{% sexy_number some_variable %}

Note: the context parameter is currently not used in my example, but I put it there to show that you can easily tweak this template tag to make it use anything that's in the template context.


The humanize app offers a nice and a quick way of formatting a number but if you need to use a separator different from the comma, it's simple to just reuse the code from the humanize app, replace the separator char, and create a custom filter. For example, use space as a separator:

@register.filter('intspace')
def intspace(value):
    """
    Converts an integer to a string containing spaces every three digits.
    For example, 3000 becomes '3 000' and 45000 becomes '45 000'.
    See django.contrib.humanize app
    """
    orig = force_unicode(value)
    new = re.sub("^(-?\d+)(\d{3})", '\g<1> \g<2>', orig)
    if orig == new:
        return new
    else:
        return intspace(new)

Slightly off topic:

I found this question while looking for a way to format a number as currency, like so:

$100
($50)  # negative numbers without '-' and in parens

I ended up doing:

{% if   var >= 0 %} ${{ var|stringformat:"d" }}
{% elif var <  0 %} $({{ var|stringformat:"d"|cut:"-" }})
{% endif %}

You could also do, e.g. {{ var|stringformat:"1.2f"|cut:"-" }} to display as $50.00 (with 2 decimal places if that's what you want.

Perhaps slightly on the hacky side, but maybe someone else will find it useful.


Well I couldn't find a Django way, but I did find a python way from inside my model:

def format_price(self):
    import locale
    locale.setlocale(locale.LC_ALL, '')
    return locale.format('%d', self.price, True)

Be aware that changing locale is process-wide and not thread safe (iow., can have side effects or can affect other code executed within the same process).

My proposition: check out the Babel package. Some means of integrating with Django templates are available.


Based on muhuk answer I did this simple tag encapsulating python string.format method.

  • Create a templatetags at your's application folder.
  • Create a format.py file on it.
  • Add this to it:

    from django import template
    
    register = template.Library()
    
    @register.filter(name='format')
    def format(value, fmt):
        return fmt.format(value)
    
  • Load it in your template {% load format %}
  • Use it. {{ some_value|format:"{:0.2f}" }}

Not sure why this has not been mentioned, yet:

{% load l10n %}

{{ value|localize }}

https://docs.djangoproject.com/en/1.11/topics/i18n/formatting/#std:templatefilter-localize

You can also use this in your Django code (outside templates) by calling localize(number).


In case someone stumbles upon this, in Django 2.0.2 you can use this

Thousand separator. Be sure to read format localization as well.

참고URL : https://stackoverflow.com/questions/346467/format-numbers-in-django-templates

반응형