def clean(self, value): """Try to coerce either a string list of values (separated by whitespace and/or commas or a list/tuple of values to a list of floats. If unsuccessful, raise a :exc:`django.forms.ValidationError` """ if value is None: return None if isinstance(value, (tuple, list)): try: value = [self.cast(x) for x in value] except (TypeError, ValueError): raise forms.ValidationError( 'Could not coerce sequence values to `float` values') elif isinstance(value, str): # it could be a string list, like this: "1, 2,3 , 4 5" # try to convert it to a an actual list and cast the values to the # chosen type if len(value) == 0: # It's an empty string list value = [] else: try: value = [self.cast(x) for x in ARRAY_RE.split(value)] except ValueError: raise forms.ValidationError( 'Could not coerce `str` to a list of `%s` values' % self.value_type) else: raise forms.ValidationError( 'Could not convert value to `list` of `%s` values: %s' % (self.value_type, value)) return value
def clean(self): super().clean() if any(self.errors): return choices = dict(HospitalNetworkDocument.CHOICES) count = {} for key, value in HospitalNetworkDocument.CHOICES: count[key] = 0 for value in self.cleaned_data: if value and not value['DELETE']: count[value['document_type']] += 1 for key, value in count.items(): if not key == HospitalNetworkDocument.ADDRESS and value > 1: raise forms.ValidationError("Only one " + choices[key] + " is allowed") if self.instance.is_billing_enabled: if '_submit_for_qc' in self.request.POST or '_qc_approve' in self.request.POST: for key, value in count.items(): if not key == HospitalNetworkDocument.GST and value < 1: raise forms.ValidationError(choices[key] + " is required")
def clean(self): if any(self.errors): return try: has_administrator = any([form.cleaned_data.get('level').user_type_id == ADMIN for form in self.forms]) except Exception: raise forms.ValidationError("Erreur critique dans la sauvegarde des membres. ") else: if not has_administrator: raise forms.ValidationError("Vous devez désigner au moins un administrateur par projet.")
def clean_upload(self): upload = self.cleaned_data['upload'] content_type = upload.content_type if content_type in settings.CONTENT_TYPES: if upload._size > settings.MAX_UPLOAD_SIZE: raise forms.ValidationError(_('Please keep filesize under %s. Current filesize %s')\ % (filesizeformat(settings.MAX_UPLOAD_SIZE), filesizeformat(upload._size))) else: raise forms.ValidationError(_('File type is not supported')) return upload
def clean_title(self): title = self.cleaned_data.get('title') if self.instance.pk: if Project.objects.filter(title=title).exclude(pk=self.instance.pk).exists(): msg = "Veuillez modifier le titre de votre projet, un projet avec ce titre existe déjà." raise forms.ValidationError(msg) else: if Project.objects.filter(title=title).exists(): msg = "Veuillez modifier le titre de votre projet, un projet avec ce titre existe déjà." raise forms.ValidationError(msg) return title
def clean(self): super().clean() cleaned_data = self.cleaned_data refund_payment = cleaned_data.get('refund_payment') refund_reason = cleaned_data.get('refund_reason') if refund_payment: if not refund_reason: raise forms.ValidationError("Refund reason is compulsory") if self.instance and not self.instance.status == self.instance.COMPLETED: raise forms.ValidationError( "Refund can be processed after Completion") # TODO : No refund should already be in process return cleaned_data
def clean(self): super().clean() if any(self.errors): return cleaned_data = self.cleaned_data state = cleaned_data.get('state', None) city_name = cleaned_data.get('name', '') if not state: raise forms.ValidationError("State is required.") if state and city_name: if MatrixMappedCity.objects.filter(name__iexact=city_name.strip(), state=state).exists(): raise forms.ValidationError( "City-State combination already exists.")
def clean_status(self): status = self.cleaned_data['status'] if status == 'ACTIVE': return 'active' elif status == 'DELETED': return 'deleted' raise forms.ValidationError('Invalid status')
def to_python(self, value): if value in self.empty_values + [renderers.JSONRenderer.format]: return None # Skip known DRF renderer formats. formats = [renderers.BrowsableAPIRenderer.format, renderers.TemplateHTMLRenderer.format] if value in formats: return query.AsText try: fn = getattr(functions, self.funcs[value]) except (KeyError, AttributeError): raise forms.ValidationError(self.error_messages['invalid_geofunc'], code='invalid_geofunc') if fn.arity and fn.arity > 1: raise forms.ValidationError('Not yet supported') return fn
def clean_full_name(self): full_name = self.cleaned_data.get('full_name', '').split(' ') full_name = [name.strip() for name in full_name if name.strip()] if len(full_name) < 2: raise forms.ValidationError(_('Fill with your full name')) return full_name
def clean_tracks(self): if not self.cleaned_data.get('tracks'): return [] try: lines = json.loads(self.cleaned_data.get('tracks')) tracks = [] for line in lines: _id = line.get('properties').get('id') if _id: track = models.Track.objects.get(id=_id) else: track = models.Track() track.track = LineString([c for c in line.get('coordinates')]) track.start = line.get('properties').get('start') track.end = line.get('properties').get('end') tracks.append(track) return tracks except ValueError, e: raise forms.ValidationError(e.message)
def pin_code_qc_submit(self): if '_submit_for_qc' in self.data: # if hasattr(self.instance, 'pin_code') and self.instance.pin_code is not None: if hasattr(self.instance, 'pin_code'): if not self.cleaned_data.get('pin_code'): raise forms.ValidationError( "Cannot submit for QC without pincode ")
def clean_email(self): email = self.cleaned_data['email'] if User.objects.filter(email=email).exists(): raise forms.ValidationError(_("Email has already been registered")) return email
def save(self, *args, **kargs): if self.instance.pk: if not self.instance.is_group_owner(self.user): raise forms.ValidationError("the request user is not the survey owner") self.instance.user = self.user return super(SurveyForm, self).save(*args, **kargs)
def clean_usuario(self): if self.cleaned_data['usuario']: p = User.objects.filter(username=self.cleaned_data['usuario']) if len(p) > 0: raise forms.ValidationError( _("Ya esxiste un usuario con este username")) return self.cleaned_data['usuario']
def _from_file(self, fileobj, tmpdir): if zipfile.is_zipfile(fileobj): with zipfile.ZipFile(fileobj) as zf: extracted = [] for item in zf.infolist(): fname = os.path.abspath(os.path.join( tmpdir, item.filename)) if fname.startswith(tmpdir): zf.extract(item, tmpdir) extracted.append(fname) for path in extracted: if path.endswith('.shp'): fname = path else: # NOTE: is_zipfile() seeks to end of file or at least 110 bytes. fileobj.seek(0) with tempfile.NamedTemporaryFile(dir=tmpdir, delete=False) as fp: shutil.copyfileobj(fileobj, fp) fname = fp.name # Attempt to union all geometries from GDAL data source. try: geoms = gdal.DataSource(fname)[0].get_geoms() geom = reduce(lambda g1, g2: g1.union(g2), geoms) if not geom.srs: raise gdal.OGRException('Cannot determine SRS') except (gdal.OGRException, gdal.OGRIndexError): raise forms.ValidationError( GeometryField.default_error_messages['invalid_geom'], code='invalid_geom') return geom
def clean_current_password(self): old = self.cleaned_data.get("current_password") if not old or check_password(old, self.user.password): return old else: raise forms.ValidationError( "Please enter your correct current password")
def clean(self): """Verifies that the values entered into the password fields match.""" cleaned_data = super(RegistrationForm, self).clean() if 'password' in cleaned_data and 'password2' in cleaned_data: if cleaned_data['password'] != cleaned_data['password2']: raise forms.ValidationError( "Passwords don't match. Please enter both fields again.") return cleaned_data
def clean_email2(self): email = self.cleaned_data.get('email') email2 = self.cleaned_data.get('email2') if email != email2: raise forms.ValidationError( _('The e-mails informed are different.')) return email
def clean(self): cleaned_data = super().clean() up_file = cleaned_data.get("attachment_file") title = cleaned_data.get("title") if up_file and not title: raise forms.ValidationError( "Veuillez donner un titre à votre pièce jointe. ") return cleaned_data
def to_python(self, value): # Need to catch GDALException with some invalid geometries, the # parent class doesn't handle all cases. try: return super(GeometryField, self).to_python(value) except gdal.GDALException: raise forms.ValidationError(self.error_messages['invalid_geom'], code='invalid_geom')
def clean_first_name(self): full_name = self.cleaned_data.get('full_name', ['']) first_name = full_name[0] if first_name: return first_name raise forms.ValidationError(_('Fill with your full name'))
def clean_password1(self): pass1 = self.cleaned_data.get('password1') if self.instance.has_usable_password() and\ self.instance.check_password(pass1): raise forms.ValidationError('A nova senha é igual a antiga') return pass1
def clean_old_password(self): old_password = self.cleaned_data.get('old_password') if not self.instance.has_usable_password() or\ self.instance.check_password(old_password): return old_password raise forms.ValidationError('A senha antiga está incorreta.')
def clean(self): super().clean() if any(self.errors): return if self.instance and self.instance.id: if self.changed_data: raise forms.ValidationError( "Cannot alter already saved remarks.")
def clean_password2(self): pass1 = self.cleaned_data.get('password1') pass2 = self.cleaned_data.get('password2') if pass1 == pass2: return pass1 raise forms.ValidationError('As senhas devem ser iguais')
def clean(self): cleaned_data = super().clean() archive_feature = cleaned_data.get('archive_feature', None) delete_feature = cleaned_data.get('delete_feature', None) if archive_feature and delete_feature and archive_feature > delete_feature: raise forms.ValidationError({ 'archive_feature': "Le délais de suppression doit être supérieur au délais d'archivage. " }) return cleaned_data
def clean_last_name(self): full_name = self.cleaned_data.get('full_name', ['']) last_parts = full_name[1:] last_name = ' '.join(last_parts) if last_name.strip(): return last_name raise forms.ValidationError(_('Fill with your full name'))
def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch'], code='password_mismatch', ) return password2
def clean_password2(self): pass1 = self.cleaned_data.get('password1') pass2 = self.cleaned_data.get('password2') if pass1 is not None: if pass1.strip() != pass2.strip(): raise forms.ValidationError( _('The passwords informed are different.')) return pass1