You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

32 lines
994 B

from django import forms
from django.core.exceptions import ValidationError
import re
from decimal import Decimal, InvalidOperation
class CurrencyInput (forms.TextInput):
def render(self, name, value, attrs=None):
if value != '':
value = u"%.2f" % value
except TypeError:
return super(CurrencyInput, self).render(name, value, attrs)
class CurrencyField (forms.RegexField):
""" Represents a currency field for django forms... or something. """
widget = CurrencyInput
currencyRe = re.compile(r'^(\+|-)?[0-9]{1,5}([,\.][0-9][0-9]?)?$')
def __init__(self, *args, **kwargs):
super(CurrencyField, self).__init__(
self.currencyRe, None, None, *args, **kwargs)
def to_python(self, value):
value = Decimal(value.replace(",", "."))
except (ValueError, TypeError, InvalidOperation):
raise ValidationError("Bitte gib eine Zahl ein")
return value
def clean(self, value):
value = super(CurrencyField, self).clean(value)
return Decimal(value)