This is an extension of the DecimalField form field that uses my Currency Object and Currency Widget.
I placed my Currency object in the Django\utils directory and the widget in Django\froms\widgets_special.py because I integrated a set of currency objects into the Admin app ( here ) and it was just easier to have everything within Django.
UPDATE 07-30-2009: Add the parse_string argument to properly test the string format as per the update to the Currency Object
UPDATE 09-15-2009: Properly handle None's in the clean method
The rest of the series: Currency Object, Currency Widget, Currency DB 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 | # -*- coding: utf-8 -*-
from django.forms import fields
from django.utils.currency import Currency, NumberFormatError
from django.forms.util import ValidationError
from django.forms import widgets_special
class CurrencyField(fields.DecimalField):
widget = widgets_special.CurrencyInput
def __init__(self, max_value=None, min_value=None, max_digits=None, *args, **kwargs):
kwargs["decimal_places"] = 2
fields.DecimalField.__init__(self, max_value, min_value, max_digits, *args, **kwargs)
def clean(self, value):
if value is None: return None
try:
value = Currency(value, parse_string=True)
except NumberFormatError, e:
raise ValidationError(e.message)
return Currency(super(CurrencyField, self).clean(value))
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 9 months ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 9 months, 1 week ago
- Serializer factory with Django Rest Framework by julio 1 year, 3 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 4 months ago
- Help text hyperlinks by sa2812 1 year, 5 months ago
Comments
Please login first before commenting.