Login

Pass db.Field to newforms.Widget

Author:
guettli
Posted:
July 20, 2007
Language:
Python
Version:
.96
Tags:
newforms i18n
Score:
0 (after 0 ratings)

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

  1. Newforms field for decimals with a comma by jonasvp 7 years, 1 month ago
  2. Filter on Multiple M2M Objects Simultaneously by axiak 8 years, 1 month ago
  3. Feet and Inches FormField/Widget by btaylordesign 4 years, 3 months ago
  4. Integer based MoneyField by Jay 5 years, 7 months ago
  5. fast non-locale aware float format by percivall 2 years, 3 months ago

Comments

guettli (on September 17, 2008):

This snippet is deprecated. I coded it long ago. Django and my django skills have evolved.

#

Please login first before commenting.