def clean(self): super(FileField, self).clean() # data) # if not self.required and data in EMPTY_VALUES: if self.value is None: return fredtypes.NullFile() if not self.required and self.value.filename in EMPTY_VALUES: return fredtypes.NullFile() if self.required and self.value.filename in EMPTY_VALUES: raise ValidationError(_(u"No file specified.")) try: # f = UploadedFile(data['filename'], data['content']) # f = fredtypes.NullFile() #UploadedFile(self.value, None) # data = self.value # f = UploadedFile(data.filename, data.file.read(-1)) f = UploadedFile(self.value.filename, self.value) except TypeError: raise ValidationError( _(u"No file was submitted. Check the encoding type on the form." )) except KeyError: raise ValidationError(_(u"No file was submitted.")) # if not f.content: # raise ValidationError(_(u"The submitted file is empty.")) return f
def clean(self): # If no URL scheme given, assume http:// value = self.value if value and '://' not in value: value = u'http://%s' % value value = super(URLField, self).clean() if value == u'': return value if self.verify_exists: import urllib2 headers = { "Accept": "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5", "Accept-Language": "en-us,en;q=0.5", "Accept-Charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.7", "Connection": "close", "User-Agent": self.user_agent, } try: req = urllib2.Request(value, None, headers) urllib2.urlopen(req) except ValueError: raise ValidationError(_(u'Enter a valid URL.')) except: # urllib2.URLError, httplib.InvalidURL, etc. raise ValidationError( _(u'This URL appears to be a broken link.')) return value
def clean(self): if self.form: if self.form.is_valid(): return self.form.cleaned_data else: raise ValidationError(_(u'Correct errors below.')) elif self.required and not self.value: raise ValidationError(_(u'This field is required.'))
def clean(self): self.create_formset_once() if self.formset: if self.formset.is_valid(): return self.formset.cleaned_data else: raise ValidationError(_(u'Correct errors below.')) elif self.required and not self.value: raise ValidationError(_(u'This field is required.'))
def compress(self, data_list): if data_list and data_list[0]: # Raise a validation error if time or date is empty # (possible if SplitDateTimeField has required=False). if data_list[0] in EMPTY_VALUES: raise ValidationError(_(u'Enter a valid date.')) if data_list[1] in EMPTY_VALUES: raise ValidationError(_(u'Enter a valid time.')) return datetime.datetime.combine(*data_list) #TODO(tom): Should we return a Null type here? return None
def clean(self): """ Check that 'To' date is bigger than 'From' date. """ to_date = self.fields['toDate'].value from_date = self.fields['fromDate'].value if from_date and to_date: if to_date < from_date: raise ValidationError( "'To' date must be bigger than 'From' date.") if 'fromDate' in self.changed_data: if from_date < datetime.date.today().isoformat(): raise ValidationError("'From' date must be in future.") return self.cleaned_data
def clean(self): """ Check that 'To' date is bigger than current date """ super(CertificationEditForm, self).clean() to_date = self.fields['toDate'].value from_date = date.today() if to_date: if ('toDate' in self.changed_data and to_date < from_date.strftime("%Y-%m-%d")): raise ValidationError( "'To' date must be bigger than current date.") if (self.initial and self.initial.get('id', None) and 'toDate' in self.changed_data): if (self.initial['toDate'].strftime("%Y-%m-%d") < self.fields['toDate'].value): raise ValidationError( "It is disallowed to lengthen the certification.") return self.cleaned_data
def clean(self): """ Validates that the input is a list or tuple. """ value = self.value if self.required and not value: raise ValidationError(_(u'This field is required.')) elif not self.required and not value: return [] if not isinstance(value, (list, tuple)): value = list(value) # Validate that each value in the value list is in self.choices. valid_values = set([unicode(k) for k, dummy_v in self.choices]) for val in value: if val not in valid_values: raise ValidationError( _(u'Select a valid choice. %s is not one of the available choices.' ) % val) return value
def clean(self): """ Validates the given value and returns its "cleaned" value as an appropriate Python object. Raises ValidationError for any errors. """ if self.required and self.value in EMPTY_VALUES: raise ValidationError(_(u'This field is required.')) return self.value
def clean(self): """ Validates that the input matches the regular expression. Returns a Unicode object. """ value = super(RegexField, self).clean() if value == u'': return value if not self.regex.search(value): raise ValidationError(self.error_message) return value
def clean(self): """Validates that float() can be called on the input. Returns a float. Returns None for empty values. """ super(FloatField, self).clean() if self.is_empty(): return fredtypes.NullFloat() try: value = float(self.value) except (ValueError, TypeError): raise ValidationError(_(u'Enter a number.')) if self.max_value is not None and value > self.max_value: raise ValidationError( _(u'Ensure this value is less than or equal to %s.') % self.max_value) if self.min_value is not None and value < self.min_value: raise ValidationError( _(u'Ensure this value is greater than or equal to %s.') % self.min_value) return value
def clean(self): "Validates max_length and min_length. Returns a Unicode object." if self.strip_spaces and isinstance(self.value, types.StringTypes): self.value = self.value.strip() super(CharField, self).clean() if self.is_empty(): return u'' value_length = len(self.value) if self.max_length is not None and value_length > self.max_length: raise ValidationError( _(u'Ensure this value has at most %(max)d characters (it has %(length)d).' ) % { 'max': self.max_length, 'length': value_length }) if self.min_length is not None and value_length < self.min_length: raise ValidationError( _(u'Ensure this value has at least %(min)d characters (it has %(length)d).' ) % { 'min': self.min_length, 'length': value_length }) return self.value
def clean(self): cleaned_data = super(AbstractIntervalField, self).clean() if cleaned_data and int( cleaned_data[3] ) == ccReg.INTERVAL._v and cleaned_data[0] and cleaned_data[ 1]: # if from and to field filled, and not day filled if cleaned_data[0] > cleaned_data[1]: # if from > to errors = ErrorList(['"From" must be bigger than "To"']) raise ValidationError(errors) cleaned_data[3] = int( cleaned_data[3]) # choicefield intervaltype type to int cleaned_data[4] = int(cleaned_data[4] or 0) # (offset) decmal to int return cleaned_data
def clean(self): """ Validates that the input is in self.choices. """ value = super(ChoiceField, self).clean() if self.is_empty(): value = u'' if value == u'': return value valid_values = set([unicode(k) for k, dummy_v in self.choices]) if value not in valid_values: raise ValidationError( _(u'Select a valid choice. That choice is not one of the available choices.' )) return value
def clean(self): """ Validates that the input can be converted to a time. Returns a Python datetime.time object. """ super(TimeField, self).clean() if self.is_empty(): return fredtypes.NullDateTime() if isinstance(self.value, datetime.time): return self.value for format in self.input_formats: try: return datetime.time(*time.strptime(self.value, format)[3:6]) except ValueError: continue raise ValidationError(_(u'Enter a valid time.'))
def clean(self): """ Validates that the input can be converted to a datetime. Returns a Python datetime.datetime object. """ super(DateTimeField, self).clean() if self.is_empty(): return fredtypes.NullDateTime() if isinstance(self.value, datetime.datetime): return self.value if isinstance(self.value, datetime.date): return datetime.datetime(self.value.year, self.value.month, self.value.day) for input_format in self.input_formats: try: return datetime.datetime.strptime(self.value, input_format) except ValueError: continue raise ValidationError(_(u'Enter a valid date/time.'))
def clean(self): """ Validates that the input is in self.choices. """ value = self.value if value == '': value = 0 if self.is_empty(): value = 0 if value == 0: return value value = int(value) if not self.validate: return value valid_values = set([k for k, _ignored_ in self.choices]) if value not in valid_values: raise ValidationError( _(u'Select a valid choice. That choice is not one of the available choices.' )) return value
def clean(self): """ Validates every value of self.fields. For example, if this MultiValueField was instantiated with fields=(DateField(), TimeField()), clean() would call DateField.clean() and TimeField.clean(). """ clean_data = [] errors = ErrorList() for field in self.fields: if self.required and field.required and field.is_empty(): raise ValidationError(_(u'This field is required.')) try: clean_data.append(field.clean()) except ValidationError, e: # Collect all validation errors in a single list, which we'll # raise at the end of clean(), rather than raising a single # exception for the first error we encounter. errors.extend(e.messages)
def clean_domains_emails(self): csv_file = self.cleaned_data['domains_emails'].content.file try: reader = csv.DictReader(csv_file) if not reader.fieldnames: raise ValidationError('Wrong file format.') if self.EMAILS_COLUMN not in reader.fieldnames: raise ValidationError('Missing column "%s" in the file.' % self.EMAILS_COLUMN) if self.ID_COLUMN not in reader.fieldnames: raise ValidationError('Missing column "%s" in the file.' % self.ID_COLUMN) domain_email_list = [] for row_num, row in enumerate( reader, start=2): # data in spreadsheet starts on line 2 if row[self.ID_COLUMN] is None: raise ValidationError( 'Missing column "%s" on the row %d.' % (self.ID_COLUMN, row_num)) if row[self.EMAILS_COLUMN] is None: raise ValidationError( 'Missing column "%s" on the row %d.' % (self.EMAILS_COLUMN, row_num)) try: domain_id = int(row[self.ID_COLUMN]) except ValueError: raise ValidationError( 'Invalid value in column Id: "%s". It must be a whole number.' % row[self.ID_COLUMN]) emails = row[self.EMAILS_COLUMN].strip() if emails.strip(): email_list = emails.split(',') for email in email_list: domain_email_list.append((domain_id, email.strip())) return domain_email_list except csv.Error, e: error('Error during reading CSV:', e) raise ValidationError('A correct CSV file is needed!')
def clean(self, data): """ Checks that the file-upload field data contains a valid image (GIF, JPG, PNG, possibly others -- whatever the Python Imaging Library supports). """ f = super(ImageField, self).clean(data) if f is None: return fredtypes.NullImage() from PIL import Image from cStringIO import StringIO try: # load() is the only method that can spot a truncated JPEG, # but it cannot be called sanely after verify() trial_image = Image.open(StringIO(f.content)) trial_image.load() # verify() is the only method that can spot a corrupt PNG, # but it must be called immediately after the constructor trial_image = Image.open(StringIO(f.content)) trial_image.verify() except Exception: # Python Imaging Library doesn't recognize it as an image raise ValidationError( _(u"Upload a valid image. The file you uploaded was either not an image or a corrupted image." )) return f
def clean(self): """ Validates that the input is a decimal number. Returns a Decimal instance. Returns None for empty values. Ensures that there are no more than max_digits in the number, and no more than decimal_places digits after the decimal point. """ super(DecimalField, self).clean() if self.is_empty(): return fredtypes.NullDecimal() value = unicode(self.value).strip() try: value = Decimal(value) except DecimalException: raise ValidationError(_(u'Enter a number.')) pieces = unicode(value).lstrip("-").split('.') decimals = (len(pieces) == 2) and len(pieces[1]) or 0 digits = len(pieces[0]) if self.max_value is not None and value > self.max_value: raise ValidationError( _(u'Ensure this value is less than or equal to %s.') % self.max_value) if self.min_value is not None and value < self.min_value: raise ValidationError( _(u'Ensure this value is greater than or equal to %s.') % self.min_value) if self.max_digits is not None and (digits + decimals) > self.max_digits: raise ValidationError( _(u'Ensure that there are no more than %s digits in total.') % self.max_digits) if self.decimal_places is not None and decimals > self.decimal_places: raise ValidationError( _(u'Ensure that there are no more than %s decimal places.') % self.decimal_places) if self.max_digits is not None and self.decimal_places is not None and digits > ( self.max_digits - self.decimal_places): raise ValidationError( _(u'Ensure that there are no more than %s digits before the decimal point.' ) % (self.max_digits - self.decimal_places)) return value
class MultiValueField(Field): """ A Field that aggregates the logic of multiple Fields. Its clean() method takes a "decompressed" list of values, which are then cleaned into a single value according to self.fields. Each value in this list is cleaned by the corresponding field -- the first value is cleaned by the first field, the second value is cleaned by the second field, etc. Once all fields are cleaned, the list of clean values is "compressed" into a single value. Subclasses should not have to implement clean(). Instead, they must implement compress(), which takes a list of valid values and returns a "compressed" version of those values -- a single value. """ tattr_list = span.tattr_list def __init__(self, name='', value='', fields=None, *args, **kwargs): # Set 'required' to False on the individual fields, because the # required validation will be handled by MultiValueField, not by those # individual fields. if fields is None: fields = [] for field in fields: field.required = False self.fields = fields self._name = '' super(MultiValueField, self).__init__(name, value, *args, **kwargs) self.tag = 'span' self.enclose_content = True def _set_name(self, value): self._name = value for i, field in enumerate(self.fields): field.name = self._name + '/%d' % i def _get_name(self): return self._name name = property(_get_name, _set_name) def _set_value(self, value): if not value: self._value = [None] * len(self.fields) for field in self.fields: field.value = None else: self._value = value if not isiterable(value) and len(value) != len(self.fields): raise TypeError( u'value of MultiValueField must be sequence with the same length as a number of fields in multifield (was % s)' % unicode(value)) for i, val in enumerate(value): self.fields[i].value = val def _get_value(self): return self._value value = LateBindingProperty(_get_value, _set_value) def make_content(self): self.content = [] for field in self.fields: label_str = field.label or '' if label_str: label_str += ':' self.add(label_str, field) def render(self, indent_level=0): self.make_content() return super(MultiValueField, self).render(indent_level) def clean(self): """ Validates every value of self.fields. For example, if this MultiValueField was instantiated with fields=(DateField(), TimeField()), clean() would call DateField.clean() and TimeField.clean(). """ clean_data = [] errors = ErrorList() for field in self.fields: if self.required and field.required and field.is_empty(): raise ValidationError(_(u'This field is required.')) try: clean_data.append(field.clean()) except ValidationError, e: # Collect all validation errors in a single list, which we'll # raise at the end of clean(), rather than raising a single # exception for the first error we encounter. errors.extend(e.messages) if errors: raise ValidationError(errors) return self.compress(clean_data)
def clean_for_time(self): if self.cleaned_data['for_time'] and self.cleaned_data[ 'for_time'] > datetime.datetime.now(): raise ValidationError( 'Record statement date must not be in the future.') return self.cleaned_data['for_time']
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, initial=None, extra_count=1, error_class=ErrorList, is_nested=False, form_class=None, layout_class=TableFormSetLayout, can_order=False, can_delete=False, *content, **kwd): super(BaseFormSet, self).__init__(*content, **kwd) if not is_nested: self.tag = u'form' else: self.tag = u'' self.is_bound = data is not None or files is not None self.prefix = prefix or 'form' self.auto_id = auto_id self.data = data self.files = files self.initial = initial self.extra_count = extra_count self.is_nested = is_nested self.error_class = error_class self.form_class = form_class self.layout_class = layout_class self.can_order = can_order self.can_delete = can_delete self._errors = None self._non_form_errors = None # initialization is different depending on whether we recieved data, initial, or nothing if data or files: self.management_form = ManagementForm(data, auto_id=self.auto_id, prefix=self.prefix, is_nested=True) if self.management_form.is_valid(): self._total_form_count = self.management_form.cleaned_data[ TOTAL_FORM_COUNT] self._initial_form_count = self.management_form.cleaned_data[ INITIAL_FORM_COUNT] else: raise ValidationError( 'ManagementForm data is missing or has been tampered with') else: if initial: self._initial_form_count = len(initial) self._total_form_count = self._initial_form_count + self.extra_count else: self._initial_form_count = 0 self._total_form_count = self.extra_count initial = { TOTAL_FORM_COUNT: self._total_form_count, INITIAL_FORM_COUNT: self._initial_form_count } self.management_form = ManagementForm(initial=initial, auto_id=self.auto_id, prefix=self.prefix) # instantiate all the forms and put them in self.forms self.forms = [] for i in range(self._total_form_count): self.forms.append(self._construct_form(i))
def clean_blacklist_to_date(self): if self.cleaned_data['blacklist_to_date'] and self.cleaned_data[ 'blacklist_to_date'] <= datetime.date.today(): raise ValidationError('Blacklist to date must be in the future.') return self.cleaned_data['blacklist_to_date']