Ticket #1553: fields.diff

File fields.diff, 9.2 KB (added by Nebojsa Djordjevic <nesh at studioquattro dot co dot yu>, 19 years ago)

patch for db/models/fields/init.py

  • store/django_no_magic/django/db/models/fields/__init__.py

     
    112112        """
    113113        if not self.blank and not field_data:
    114114            return [gettext_lazy('This field is required.')]
     115        # XXX IMHO this is the place for NULL validation, to_python will return '' (blank) or None as appropriate
     116        if not self.null and field_data is None:
     117            return [gettext_lazy('This field is required.')]
    115118        try:
    116119            self.validate(field_data, all_data)
    117120        except validators.ValidationError, e:
     
    331334    def __init__(self, *args, **kwargs):
    332335        assert kwargs.get('primary_key', False) is True, "%ss must have primary_key=True." % self.__class__.__name__
    333336        kwargs['blank'] = True
     337        # added because validators
     338        kwargs['null'] = True
    334339        Field.__init__(self, *args, **kwargs)
    335340
    336341    def to_python(self, value):
     
    368373        Field.__init__(self, *args, **kwargs)
    369374
    370375    def to_python(self, value):
     376        if value is None:
     377            raise validators.ValidationError, gettext("This value can not be None.")
    371378        if value in (True, False): return value
     379        if value == '': return False
    372380        if value is 't': return True
    373381        if value is 'f': return False
    374382        raise validators.ValidationError, gettext("This value must be either True or False.")
     
    383391    def to_python(self, value):
    384392        if isinstance(value, basestring):
    385393            return value
    386         if value is None:
    387             if self.null:
    388                 return value
    389             else:
    390                 raise validators.ValidationError, gettext_lazy("This field cannot be null.")
     394        if value is None: return value
    391395        return str(value)
     396   
     397    def validate(self, field_data, all_data):
     398        if not field_data: return
     399        if self.maxlength < len(field_data):
     400            raise validators.ValidationError, gettext_lazy("Maximum string length exceeded.")
    392401
    393402# TODO: Maybe move this into contrib, because it's specialized.
    394403class CommaSeparatedIntegerField(CharField):
     
    395404    def get_manipulator_field_objs(self):
    396405        return [forms.CommaSeparatedIntegerField]
    397406
     407    def to_python(self, value):
     408        value = super(CommaSeparatedIntegerField, self).to_python(value)
     409        if not value: return []
     410        try:
     411            return [int(l) for l in value.split(',')]
     412        except (TypeError, ValueError):
     413            raise ValidationError, gettext("Enter a whole number.")
     414
     415    def validate(self, field_data, all_data):
     416        if not field_data: return
     417        # XXX hmmm, I presume that maxlength here means the maximum entries
     418        if self.maxlength < len(field_data):
     419            raise validators.ValidationError, gettext_lazy("Exceeded maximum number of entries.")
     420
     421
    398422class DateField(Field):
    399423    empty_strings_allowed = False
    400424    def __init__(self, verbose_name=None, name=None, auto_now=False, auto_now_add=False, **kwargs):
     
    406430        Field.__init__(self, verbose_name, name, **kwargs)
    407431
    408432    def to_python(self, value):
     433        if value is None or value == '': return None
    409434        if isinstance(value, datetime.datetime):
    410435            return value.date()
    411436        if isinstance(value, datetime.date):
     
    457482
    458483class DateTimeField(DateField):
    459484    def to_python(self, value):
     485        if value is None or value == '': return None
    460486        if isinstance(value, datetime.datetime):
    461487            return value
    462488        if isinstance(value, datetime.date):
     
    625651    def get_manipulator_field_objs(self):
    626652        return [curry(forms.FloatField, max_digits=self.max_digits, decimal_places=self.decimal_places)]
    627653
     654    def to_python(self, value):
     655        import decimal
     656        if value is None or value == '': return None
     657        try:
     658            return decimal.Decimal(value)
     659        except (TypeError, ValueError):
     660            raise validators.ValidationError, gettext_lazy("Enter a float number.")
     661
     662    def validate(self, field_data, all_data):
     663        if len('%.0f' % abs(field_data)) > self.max_digits:
     664            raise validators.ValidationError, gettext_lazy("Too many digits.")
     665
    628666class ImageField(FileField):
    629667    def __init__(self, verbose_name=None, name=None, width_field=None, height_field=None, **kwargs):
    630668        self.width_field, self.height_field = width_field, height_field
     
    659697    def get_manipulator_field_objs(self):
    660698        return [forms.IntegerField]
    661699
     700    def to_python(self, value):
     701        if value is None or value == '': return None
     702        try:
     703            return int(value)
     704        except (TypeError, ValueError):
     705            raise validators.ValidationError, gettext_lazy("Enter a whole number.")
     706
    662707class IPAddressField(Field):
    663708    def __init__(self, *args, **kwargs):
    664709        kwargs['maxlength'] = 15
     
    678723    def get_manipulator_field_objs(self):
    679724        return [forms.NullBooleanField]
    680725
     726    def to_python(self, value):
     727        if value is None or value == '': return None
     728        if value in (True, False): return value
     729        if value is 't': return True
     730        if value is 'f': return False
     731        raise validators.ValidationError, gettext("This value must be either True or False.")
     732
    681733class PhoneNumberField(IntegerField):
    682734    def get_manipulator_field_objs(self):
    683735        return [forms.PhoneNumberField]
     
    689741    def get_manipulator_field_objs(self):
    690742        return [forms.PositiveIntegerField]
    691743
     744    def to_python(self, value):
     745        if value is None or value == '': return None
     746        try:
     747            return int(value)
     748        except (TypeError, ValueError):
     749            raise validators.ValidationError, gettext_lazy("Enter a whole number.")
     750
     751    def validate(self, field_data, all_data):
     752        if field_data < 0:
     753            raise validators.ValidationError, gettext_lazy("Enter a whole positive number.")
     754
    692755class PositiveSmallIntegerField(IntegerField):
    693756    def get_manipulator_field_objs(self):
    694757        return [forms.PositiveSmallIntegerField]
     
    693756    def get_manipulator_field_objs(self):
    694757        return [forms.PositiveSmallIntegerField]
    695758
     759    def to_python(self, value):
     760        if value is None or value == '': return None
     761        try:
     762            return int(value)
     763        except (TypeError, ValueError):
     764            raise validators.ValidationError, gettext_lazy("Enter a whole number.")
     765
     766    def validate(self, field_data, all_data):
     767        if field_data < 0:
     768            raise validators.ValidationError, gettext_lazy("Enter a whole positive number.")
     769
    696770class SlugField(Field):
    697771    def __init__(self, *args, **kwargs):
    698772        kwargs['maxlength'] = 50
     
    705779    def get_manipulator_field_objs(self):
    706780        return [forms.TextField]
    707781
     782    def validate(self, field_data, all_data):
     783        validators.isSlug(field_data, all_data)
     784
    708785class SmallIntegerField(IntegerField):
    709786    def get_manipulator_field_objs(self):
    710787        return [forms.SmallIntegerField]
     
    709786    def get_manipulator_field_objs(self):
    710787        return [forms.SmallIntegerField]
    711788
     789    def to_python(self, value):
     790        if value is None or value == '': return None
     791        try:
     792            return int(value)
     793        except (TypeError, ValueError):
     794            raise validators.ValidationError, gettext_lazy("Enter a whole number.")
     795
    712796class TextField(Field):
    713797    def get_manipulator_field_objs(self):
    714798        return [forms.LargeTextField]
     
    750834        val = self._get_val_from_obj(obj)
    751835        return {self.attname: (val is not None and val.strftime("%H:%M:%S") or '')}
    752836
     837    def to_python(self, value):
     838        if value is None or value == '': return None
     839        try:
     840            st = time.strptime(value, '%H:%M:%S')
     841            return datetime.time(st.tm_hour, st.tm_min, st.tm_sec)
     842        except (TypeError, ValueError):
     843            raise validators.ValidationError, gettext_lazy("Enter a whole number.")
     844
    753845class URLField(Field):
    754846    def __init__(self, verbose_name=None, name=None, verify_exists=True, **kwargs):
    755847        if verify_exists:
     
    754846    def __init__(self, verbose_name=None, name=None, verify_exists=True, **kwargs):
    755847        if verify_exists:
    756848            kwargs.setdefault('validator_list', []).append(validators.isExistingURL)
     849        self.verify_exists = verify_exists
    757850        Field.__init__(self, verbose_name, name, **kwargs)
    758851
    759852    def get_manipulator_field_objs(self):
     
    759852    def get_manipulator_field_objs(self):
    760853        return [forms.URLField]
    761854
     855    def to_python(self, value):
     856        if isinstance(value, basestring): return value
     857        if value is None: return value
     858        return str(value)
     859   
     860    def validate(self, field_data, all_data):
     861        validators.isValidURL(field_data, all_data)
     862        if self.verify_exists:
     863            validators.isExistingURL(field_data, all_data)
     864
    762865class USStateField(Field):
    763866    def get_manipulator_field_objs(self):
    764867        return [forms.USStateField]
Back to Top