Login

Integer Currency Input

Author:
jgeewax
Posted:
September 4, 2008
Language:
Python
Version:
1.0
Score:
2 (after 2 ratings)

This accepts values such as $1,000,000 and stores them to the database as integers. It also re-renders them to the screen using the django.contrib.humanize.intcomma method which takes 1000000 and turns it into 1,000,000. Useful for large currency fields where the decimals aren't really necessary.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class IntegerCurrencyInput(forms.TextInput):
    def render(self, name, value, attrs=None):
        from django.contrib.humanize.templatetags.humanize import intcomma
        if value:
            value = "$%s" % intcomma(value)
        return super(IntegerCurrencyInput, self).render(name, value, attrs)

class IntegerCurrencyField(forms.IntegerField):
    widget = IntegerCurrencyInput
    
    def clean(self, value):
        if value:
            if value[0] == "$": value = value[1:] # Cut off the dollar sign
            value = value.replace(',', '') # Remove Commas
        value = super(IntegerCurrencyField, self).clean(value)
        return int(value) if value else value

More like this

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

Comments

Please login first before commenting.