Ticket #9893: filefield_length_validation.diff

File filefield_length_validation.diff, 1.7 KB (added by Carson Gee, 14 years ago)
  • django/db/models/fields/files.py

     
    1313from django.db.models import signals
    1414from django.utils.encoding import force_unicode, smart_str
    1515from django.utils.translation import ugettext_lazy, ugettext as _
     16from django.core.exceptions import ValidationError
    1617from django import forms
    1718from django.db.models.loading import cache
    1819
     
    210211        instance.__dict__[self.field.name] = value
    211212
    212213class FileField(Field):
     214
     215    default_error_messages = {
     216        'max_length': ugettext_lazy(u'Ensure this filename and path has at most %(max)d characters (it has %(length)d).')
     217        }
     218
    213219    # The class to wrap instance attributes in. Accessing the file object off
    214220    # the instance will always return an instance of attr_class.
    215221    attr_class = FieldFile
     
    232238        kwargs['max_length'] = kwargs.get('max_length', 100)
    233239        super(FileField, self).__init__(verbose_name, name, **kwargs)
    234240
     241    def validate(self, value, model_instance):
     242        """
     243        Validates that the file name plus the path still fits within max_length
     244        of the field.  It throws a ValidationError if it doesn't.
     245        """
     246       
     247        length = len(self.generate_filename(model_instance, value.name))
     248        if self.max_length and length > self.max_length:
     249            error_values = {'max': self.max_length, 'length': length }
     250            raise ValidationError(self.error_messages['max_length'] % error_values)
     251
    235252    def get_internal_type(self):
    236253        return "FileField"
    237254
Back to Top