Login

(en-US) Humanized Decimal Field

Author:
ActionScripted
Posted:
July 1, 2008
Language:
Python
Version:
.96
Tags:
comma field decimal separator input humanize thousands form
Score:
3 (after 3 ratings)

Simple DecimalField class extension that automatically adds formatting and validation for comma-separated "decimals". Works wonderfully for price fields.

Could be extended to strip dollar signs or to be locale-agnostic.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
""" Stay DRY, import intcomma """
from django.contrib.humanize.templatetags.humanize import intcomma


class USDecimalHumanizedInput(forms.TextInput):
  def __init__(self, initial=None, *args, **kwargs):
    super(USDecimalHumanizedInput, self).__init__(*args, **kwargs)
  
  def render(self, name, value, attrs=None):
    value = intcomma(value)
    return super(USDecimalHumanizedInput, self).render(name, value, attrs)


class USDecimalHumanizedField(forms.DecimalField):
  """
  Use this as a drop-in replacement for forms.DecimalField()
  """
  widget = USDecimalHumanizedInput
  
  def clean(self, value):
    value = value.replace(',','')
    super(USDecimalHumanizedField, self).clean(value)
    return value

More like this

  1. Newforms field for decimals with a comma by jonasvp 7 years, 5 months ago
  2. format_thousands by cootetom 4 years, 2 months ago
  3. Comma separated users field by sopelkin 7 years, 6 months ago
  4. Many2Many comma separated form field by haloween 5 years, 7 months ago
  5. Converts an integer or floating-point number or a string to a string containing the delimiter character (default comma) after every delimeter_count digits (by default 3 digits) by pikhovkin 3 years, 5 months ago

Comments

ActionScripted (on July 2, 2008):

I've noticed that when initializing without an explicit initial value, the field defaults to the string "None".

Not sure how to change this, but it'd be great if it would just fall-back to an empty string ("").

#

Davepar (on July 15, 2010):

Line 22 should be:

value = super(USDecimalHumanizedField, self).clean(value)

Otherwise the value never gets turned into a Decimal type.

#

hobbesdaboba (on June 14, 2011):

Just in case anyone still uses this, to fix the "None" problem mentioned by ActionScripted, simply change line 10 so that:

if value: value = intcomma(value) else: value = ''

#

Please login first before commenting.