Skip to content

Instantly share code, notes, and snippets.

@gladson
Forked from igorsobreira/formatters.py
Last active August 29, 2015 13:57
Show Gist options
  • Save gladson/9379320 to your computer and use it in GitHub Desktop.
Save gladson/9379320 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
from django.template.defaultfilters import floatformat
from django.contrib.humanize.templatetags.humanize import intcomma
from django.utils.encoding import force_unicode
from django.template import Library
register = Library()
@register.filter(name='float_to_real')
def float_to_real(value, precision):
'''
Receives a Float instance and returns a string formatted as brazilian Real currency:
12.345,67. Without the "R$".
'''
value_arg = floatformat(value, precision)
value_arg, float_arg = force_unicode(value_arg).split(',')
value_arg = intcomma(value_arg)
value_arg = value_arg + ',' + float_arg
return value_arg
from django import forms
from widgets import RealCurrencyInput
class RealCurrencyField(forms.DecimalField):
widget = RealCurrencyInput
def clean(self, value):
if value:
value = value.replace('.', '').replace(',','.')
return super(RealCurrencyField, self).clean(value)
def widget_attrs(self, widget):
return {'class':'real_currency'}
from decimal import Decimal
from django import forms
from django.utils.safestring import mark_safe
from formatters import decimal_to_real
class RealCurrencyInput(forms.TextInput):
def render(self, name, value, attrs=None):
value = value or ''
if isinstance(value, Decimal):
value = decimal_to_real(str(value), 2)
attrs = attrs or {}
attrs['class'] = 'real'
attrs['alt'] = 'decimal'
html = super(RealCurrencyInput, self).render(name, value, attrs)
return mark_safe(u"R$ " + html)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment