Login

Pass db.Field to newforms.Widget

Author:
guettli
Posted:
July 20, 2007
Language:
Python
Version:
.96
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. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 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.