Percent Field

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
from django.forms import IntegerField
from django.forms.widgets import Input
from django.forms.util import ValidationError
from django.utils.translation import ugettext_lazy as _
from decimal import Decimal

class PercentInput(Input):
    """ A simple form input for a percentage """
    input_type = 'text'

    def _format_value(self, value):
        if value is None:
            return ''
        return str(int(value * 100))

    def render(self, name, value, attrs=None):
        value = self._format_value(value)
        return super(PercentInput, self).render(name, value, attrs)

    def _has_changed(self, initial, data):
        return super(PercentInput, self)._has_changed(self._format_value(initial), data)

class PercentField(IntegerField):
    """ A field that gets a value between 0 and 1 and displays as a value between 0 and 100"""
    widget = PercentInput(attrs={"class": "percentInput", "size": 4})

    default_error_messages = {
        'positive': _(u'Must be a positive number.'),
    }

    def clean(self, value):
        """
        Validates that the input can be converted to a value between 0 and 1.
        Returns a Decimal
        """
        value = super(PercentField, self).clean(value)
        if value is None:
            return None
        if (value < 0):
            raise ValidationError(self.error_messages['positive'])
        return Decimal("%.2f" % (value / 100.0))

More like this

  1. Converting datetime to Javascript milliseconds in epoch by guychi 6 years, 8 months ago
  2. ByteSplitterField by Lacour 2 years, 8 months ago
  3. Django admin autoregister by Mimino 5 months, 2 weeks ago
  4. RequiredNullBooleanField by wwu.housing 5 years, 1 month ago
  5. Coalesce for F() by axil 2 years, 2 months ago

Comments

renaud (on August 3, 2010):

hi Fybl, thanks for posting your snippet. I added:

l.12\ if value is None or value == "":

l18 return super(PercentInput, self).render(name, value, attrs) + mark_safe(u' %')

#

(Forgotten your password?)