root / snf-common / synnefo / lib / db / intdecimalfield.py @ c11dc0ce
History | View | Annotate | Download (1.6 kB)
1 |
from django.core import exceptions |
---|---|
2 |
from django.db.models import DecimalField, SubfieldBase |
3 |
from django.utils.translation import ugettext_lazy as _ |
4 |
import decimal |
5 |
|
6 |
class IntDecimalField(DecimalField): |
7 |
|
8 |
__metaclass__ = SubfieldBase |
9 |
|
10 |
description = _("Integer number as decimal")
|
11 |
|
12 |
def to_python(self, value): |
13 |
if value is None: |
14 |
return value
|
15 |
try:
|
16 |
return long(value) |
17 |
except (ValueError, TypeError): |
18 |
raise exceptions.ValidationError(self.error_messages['invalid']) |
19 |
|
20 |
def _to_decimal(self, value): |
21 |
if value is None: |
22 |
return value
|
23 |
try:
|
24 |
return decimal.Decimal(value)
|
25 |
except decimal.InvalidOperation:
|
26 |
raise exceptions.ValidationError(self.error_messages['invalid']) |
27 |
|
28 |
def get_db_prep_save(self, value, connection): |
29 |
return connection.ops.value_to_db_decimal(self._to_decimal(value), |
30 |
self.max_digits, self.decimal_places) |
31 |
|
32 |
def get_prep_value(self, value): |
33 |
return self._to_decimal(value) |
34 |
|
35 |
def formfield(self, **kwargs): |
36 |
defaults = {'form_class': forms.IntegerField}
|
37 |
defaults.update(kwargs) |
38 |
return super(IntegerField, self).formfield(**defaults) |
39 |
|
40 |
from south.modelsinspector import add_introspection_rules |
41 |
add_introspection_rules([], ["^synnefo\.lib\.db\.intdecimalfield\.IntDecimalField"])
|
42 |
|
43 |
DECIMAL_DIGITS = 38
|
44 |
|
45 |
def intDecimalField(**kwargs): |
46 |
# decimal_places is set here instead of the object constructor
|
47 |
# in order to convince south
|
48 |
return IntDecimalField(max_digits=DECIMAL_DIGITS, decimal_places=0, **kwargs) |