Deprecated. I don't use this any more.
Hi,
I want decimal input which uses a comma as decimal seperator. It was quite complicated, but it works.
It can be used as an example how to create an own subclass of an existing db.Field class and how to pass the dbfield to the widget, and use it in its render() method.
I think my snippet is too complicated, but couldn't find a better solution. If you do, please tell me.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | # Python Imports
import new
import django.newforms as forms
from django.db.models.fields import DecimalField
decimal_delimiter=","
class CustomInput(forms.widgets.TextInput):
def render(self, name, value, attrs=None):
if value and not isinstance(value, basestring):
value=self.dbfield.format_number(value).replace(".", decimal_delimiter)
return forms.widgets.TextInput.render(self, name, value, attrs=attrs)
class I18NDecimalHTMLField(forms.DecimalField):
def __init__(self, *args, **kwargs):
self.widget = CustomInput()
self.widget.dbfield=self.dbfield
forms.DecimalField.__init__(self, *args, **kwargs)
def clean(self, value):
if not self.required and value in forms.fields.EMPTY_VALUES:
return None
value = value.strip()
value=value.replace(decimal_delimiter, ".")
return forms.DecimalField.clean(self, value)
class I18NDecimalField(DecimalField):
def formfield(self, **kwargs):
# You can only pass a form.Field class. That's why I
# create a new class here.
form_class=new.classobj("I18NDecimalHTMLField-%d" % self.decimal_places,
(I18NDecimalHTMLField,), globals())
form_class.dbfield=self
defaults = {
'max_digits': self.max_digits,
'decimal_places': self.decimal_places,
'form_class': form_class
}
defaults.update(kwargs)
return super(DecimalField, self).formfield(**defaults)
def get_internal_type(self):
return 'DecimalField'
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
This snippet is deprecated. I coded it long ago. Django and my django skills have evolved.
#
Please login first before commenting.