Login

Currency Form Field

Author:
Rupe
Posted:
May 25, 2009
Language:
Python
Version:
1.0
Score:
0 (after 0 ratings)

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

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 8 months ago

Comments

Please login first before commenting.