Currency DB 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
42
43
44
45
46
47
48
import decimal
from django.db.models import fields
from django.db.models.fields.subclassing import SubfieldBase
from django.forms import fields_special
from django.utils.currency import Currency
from django.utils.translation import ugettext as _

class CurrencyField(fields.DecimalField):

    __metaclass__ = SubfieldBase

    def __init__(self,  verbose_name=None, name=None, max_digits=None, *args, **kwargs):
        if not kwargs.has_key("help_text"):
            kwargs['help_text'] = _('Format: ') + Currency(9999.00).format()
        decimal_places = 2
        if kwargs.has_key('decimal_places'):
            del kwargs['decimal_places']
        fields.DecimalField.__init__(self, verbose_name, name, max_digits, decimal_places, *args, **kwargs)

    def format(self):
        return Currency(self).format()

    def format_number(self, value):
        return Currency(value).format()

    def formfield(self, **kwargs):
        defaults = {
            'form_class': fields_special.CurrencyField,
        }
        defaults.update(kwargs)
        return super(CurrencyField, self).formfield(**defaults)

    def to_python(self, value):
        if value is None:
            return value
        try:
            return Currency(value)
        except decimal.InvalidOperation:
            raise decimal.InvalidOperation(
                _("This value must be a decimal number."))

    def value_to_string(self, obj):
        val = self._get_val_from_obj(obj)
        if val is None:
            data = ''
        else:
            data = str(val)
        return data

More like this

  1. Currency Widget by Rupe 4 years, 11 months ago
  2. Currency Form Field by Rupe 4 years, 11 months ago
  3. Currency Field Admin Integration by Rupe 4 years, 11 months ago
  4. Currency Object by Rupe 4 years, 11 months ago
  5. autocompleter with database query by bbolli 6 years, 9 months ago

Comments

(Forgotten your password?)