Login

Newforms field for decimals with a comma

Author:
jonasvp
Posted:
March 12, 2008
Language:
Python
Version:
.96
Tags:
newforms locale comma decimal
Score:
4 (after 4 ratings)

This might be handy in countries where decimals are entered with a comma separating the decimal places from the integer part (for instance in Germany). It lets user enter and displays all decimals with a comma separator.

I ran into this problem and couldn't find a clean internationalized way of doing it... but newforms makes it so easy to roll your own. Hope it helps someone.

 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

Comments

mike_dibernardo (on March 12, 2008):
<p>Nice. We should band together and make an extended grab-bag of formfields that people would find helpful.</p>

#

jonasvp (on March 17, 2008):
<p>Good idea. Who's up for programming a djangofields.org-site? ;-)</p> <p>Also, there's a small bug in this widget. Line 6 has to read</p> <p>return super(CommaWidget, self).render(name, smart_str(value).replace('.', ','), attrs)</p> <p>Sorry about that.</p>

#

reyx (on July 29, 2012):
<p>How about None values, when null=True in model?</p> <pre>return super(CommaWidget, self).render(name, '' if value is None else smart_str(value).replace('.', ','), attrs) </pre>

#

Please login first before commenting.