This is an extension of the DecimalField database field that uses my Currency Object, Currency Widget, and Currency Form Field.
I placed my Currency object in the Django\utils directory, the widget in Django\froms\widgets_special.py, and the form field in Django\forms\fields_special.py because I integrated this set of currency objects into the Admin app ( here ) and it was just easier to have everything within Django.
UPDATE 08-18-2009: Added 'import decimal' and modified to_python slightly.
The rest of the series: Currency Object, Currency Widget, Currency Form Field, Admin Integration
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
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 8 months ago
Comments
Please login first before commenting.