List Info

Thread: newforms validation




newforms validation
user name
2006-12-29 15:17:18
I tried to implement what I want, please review (this
example works for
me):

patch:
Index: fields.py
============================================================
=======
--- fields.py	(revision 4253)
+++ fields.py	(working copy)
 -33,7
+33,7 
     # Tracks each time a Field instance is created. Used to
retain
order.
     creation_counter = 0

-    def __init__(self, required=True, widget=None,
label=None,
initial=None):
+    def __init__(self, required=True, widget=None,
label=None,
initial=None, validator_list=[]):
         # required -- Boolean that specifies whether the
field is
required.
         #             True by default.
         # widget -- A Widget class, or instance of a Widget
class,
that should be
 -72,6
+72,9 
         """
         if self.required and value in EMPTY_VALUES:
             raise ValidationError(gettext(u'This field is
required.'))
+        for validator in self.validator_list:
+            validator(value)
+
         return value

     def widget_attrs(self, widget):
 -83,8
+86,8 
         return {}

 class CharField(Field):
-    def __init__(self, max_length=None, min_length=None,
required=True, widget=None, label=None, initial=None):
-        self.max_length, self.min_length = max_length,
min_length
+    def __init__(self, max_length=None, min_length=None,
required=True, widget=None, label=None, initial=None,
validator_list=[]):
+        self.max_length, self.min_length,
self.validator_list =
max_length, min_length, validator_list
         Field.__init__(self, required, widget, label,
initial)

     def clean(self, value):


usage:

#-----------------------------------------------------------
--------------------

def isSomething( value ):
    if( value != 'something' ):
        raise ValidationError, gettext( "not
something!." )

#-----------------------------------------------------------
--------------------

class AddChangeProductForm( forms.Form ):
    '''
    form used for creating or renaming a product
    '''
    name = forms.CharField( validator_list = [ isSomething ]
)

#-----------------------------------------------------------
--------------------


p.s. I'm relatevely new to python, so let your critics be
constructive.
thanks.


--~--~---------~--~----~------------~-------~--~----~
 You received this message because you are subscribed to the
Google Groups "Django users" group.
To post to this group, send email to django-usersgooglegroups.com
To unsubscribe from this group, send email to
django-users-unsubscribegooglegroups.com
For more options, visit this group at htt
p://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

[1]

about | contact  Other archives ( Real Estate discussion Medical topics )