Newforms field for decimals with a comma

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
from django import newforms as forms
from django.utils.encoding import smart_str

class CommaWidget(forms.widgets.TextInput):
    def render(self, name, value, attrs=None):
        return super(CommaWidget, self).render(name, smart_str(value).replace('.', ','))


class CommaDecimalField(forms.DecimalField):
    """
    Extension to DecimalField that allows comma-separated Decimals to be entered and displayed
    """
    widget = CommaWidget
    
    def clean(self, value):
        value = smart_str(value).replace(',', '.')
        return super(CommaDecimalField, self).clean(value)

More like this

  1. Pass db.Field to newforms.Widget by guettli 5 years, 10 months ago
  2. SeparatedValuesField by jezdez 5 years, 5 months ago
  3. (en-US) Humanized Decimal Field by ActionScripted 4 years, 10 months ago
  4. Feet and Inches FormField/Widget by btaylordesign 2 years, 4 months ago
  5. Create multiple related objects at once by yaniv.haber 4 years, 1 month ago

Comments

mike_dibernardo (on March 12, 2008):

Nice. We should band together and make an extended grab-bag of formfields that people would find helpful.

#

jonasvp (on March 17, 2008):

Good idea. Who's up for programming a djangofields.org-site? ;-)

Also, there's a small bug in this widget. Line 6 has to read

return super(CommaWidget, self).render(name, smart_str(value).replace('.', ','), attrs)

Sorry about that.

#

reyx (on July 29, 2012):

How about None values, when null=True in model?

return super(CommaWidget, self).render(name, '' if value is None else smart_str(value).replace('.', ','), attrs)

#

(Forgotten your password?)