Login

Percent Field

Author:
fylb
Posted:
February 9, 2010
Language:
Python
Version:
1.1
Tags:
field percent
Score:
2 (after 2 ratings)

This can be used in a forms.Form or forms.ModelForm in django. Render a decimal field between 0 and 1 into a value between 0 and 100, and vice-versa.

 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. FileField mismatches by depaolim 8 months, 4 weeks ago
  2. Converting datetime to Javascript milliseconds in epoch by guychi 8 years ago
  3. ByteSplitterField by Lacour 4 years ago
  4. RequiredNullBooleanField by wwu.housing 6 years, 5 months ago
  5. Filter changelist by a numeric field using a number of common value ranges by asfaltboy 15 hours, 34 minutes 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' %')

#

Please login first before commenting.