def validate_fk(queryset, request, filter, value, to_field, error_messages): try: return query_filter(request, queryset, filter).get(**{to_field: value}) except ObjectDoesNotExist: message = error_messages['invalid'] if 'invalid' in error_messages else _(u'Select a valid choice. %s is not one of the available choices.') % value x = ValidationError(message) x.code = 'invalid_choice' raise x except ValueError: message = error_messages['invalid_pk_value'] % value x = ValidationError(message) x.code = 'invalid_pk_value' raise x except Exception as e: message = e.message x = ValidationError(message) x.code = 'other' raise x
def validate_m2m(queryset, request, filter, values, to_field, error_messages): v = 0 try: vs = [] t = query_filter(request, queryset, filter) for v in values: vs.append(t.get(**{to_field: v})) return vs except ObjectDoesNotExist: message = error_messages['invalid_choice'] if 'invalid_choice' in error_messages else _(u'Select a valid choice. %s is not one of the available choices.') % v x = ValidationError(message) x.code = 'invalid_choice' raise x except ValueError: message = error_messages['invalid_pk_value'] % v x = ValidationError(message) x.code = 'invalid_pk_value' raise x except Exception as e: message = e.message x = ValidationError(message) x.code = 'other' raise x
def clean_teacher(self): try: teacher = User.objects.get(email=self.cleaned_data.get('teacher')) except User.DoesNotExist: raise ValidationError("El usuario no existe 😢") return teacher
def __init__(self, request, *args, **kwargs): super(CreateImageForm, self).__init__(request, *args, **kwargs) if (api.glance.get_image_upload_mode() == 'off' or not policy.check( (("image", "upload_image"), ), request)): self._hide_file_source_type() if not policy.check((("image", "set_image_location"), ), request): self._hide_url_source_type() # GlanceV2 feature removals if api.glance.VERSIONS.active >= 2: # NOTE: GlanceV2 doesn't support copy-from feature, sorry! self._hide_is_copying() if not settings.IMAGES_ALLOW_LOCATION: self._hide_url_source_type() if (api.glance.get_image_upload_mode() == 'off' or not policy.check( (("image", "upload_image"), ), request)): # Neither setting a location nor uploading image data is # allowed, so throw an error. msg = _('The current Horizon settings indicate no valid ' 'image creation methods are available. Providing ' 'an image location and/or uploading from the ' 'local file system must be allowed to support ' 'image creation.') messages.error(request, msg) raise ValidationError(msg) if not policy.check((("image", "publicize_image"), ), request): self._hide_is_public() self.fields['disk_format'].choices = \ api.glance.get_image_formats(request) try: kernel_images = api.glance.image_list_detailed( request, filters={'disk_format': 'aki'})[0] except Exception: kernel_images = [] msg = _('Unable to retrieve image list.') messages.error(request, msg) if kernel_images: choices = [('', _("Choose an image"))] for image in kernel_images: choices.append((image.id, image)) self.fields['kernel'].choices = choices else: del self.fields['kernel'] try: ramdisk_images = api.glance.image_list_detailed( request, filters={'disk_format': 'ari'})[0] except Exception: ramdisk_images = [] msg = _('Unable to retrieve image list.') messages.error(request, msg) if ramdisk_images: choices = [('', _("Choose an image"))] for image in ramdisk_images: choices.append((image.id, image)) self.fields['ramdisk'].choices = choices else: del self.fields['ramdisk']
def clean(self, value): if value != VALID_VALUE: raise ValidationError(_('Typed characters does not match with the ones in the image'))
def clean_terms_accepted(self): if not self.cleaned_data['terms_accepted']: raise ValidationError(_("Terms not accepted")) return True
def clean_content(self): """Check if content is empty.""" if self.cleaned_data['content'] != '': raise ValidationError('Invalid value') return ''
def clean_textid(self): if not re.match('^[a-z0-9_]*$', self.cleaned_data['textid']): raise ValidationError( 'Only lowerchase characters, numbers and underscore allowed!') return self.cleaned_data['textid']
def clean_name(self): cleaned_name = self.cleaned_data['name'] if cleaned_name.isspace(): raise ValidationError(_('Group type name can not be empty.')) return cleaned_name
def done(self, form_list, **kwargs): form_dict = kwargs.get('form_dict') if self.request.user.is_authenticated: user = self.request.user else: uid = form_dict['user'].save() user = User.objects.filter(pk=uid).first() if not user or not user.is_active: raise ValidationError( _('There was an error when logging in. Please contact the organiser for further help.' ), ) form_dict['info'].instance.event = self.request.event form_dict['info'].save() form_dict['info'].instance.speakers.add(user) sub = form_dict['info'].instance form_dict['profile'].user = user form_dict['profile'].save() if 'questions' in form_dict: for k, value in form_dict['questions'].cleaned_data.items(): qid = k.split('_')[1] self._handle_question_answer(sub, qid, value, user=user) try: sub.event.ack_template.to_mail( user=user, event=self.request.event, context=template_context_from_submission(sub), skip_queue=True, locale=user.locale, submission=sub, full_submission_content=True, ) if self.request.event.settings.mail_on_new_submission: MailTemplate( event=self.request.event, subject=_('New submission!').format( event=self.request.event.slug), text=self.request.event.settings.mail_text_new_submission, ).to_mail( user=self.request.event.email, event=self.request.event, context=template_context_from_submission(sub), skip_queue=True, locale=self.request.event.locale, ) additional_speaker = form_dict['info'].cleaned_data.get( 'additional_speaker') if additional_speaker: sub.send_invite(to=[additional_speaker], _from=user) except SendMailException as exception: logging.getLogger('').warning(str(exception)) messages.warning(self.request, phrases.cfp.submission_email_fail) sub.log_action('pretalx.submission.create', person=user) messages.success(self.request, phrases.cfp.submission_success) login(self.request, user, backend='django.contrib.auth.backends.ModelBackend') return redirect( reverse('cfp:event.user.submissions', kwargs={'event': self.request.event.slug}))
def clean_file(self): try: return json.load(self.cleaned_data["file"]) except: raise ValidationError("Must be proper json", code="badjson")
def clean(self): raise ValidationError("This is a non-form error")
def clean(self): raise ValidationError("Clean method called")
def to_python(self, data): """Check that the file-upload field data contains a valid image (GIF, JPG, PNG, etc. -- whatever Pillow supports). Vendored from django.forms.fields.ImageField to add EXIF data removal. Can't use super() because we need to patch in the .png.fp object for some unholy (and possibly buggy) reason. """ f = super().to_python(data) if f is None: return None # We need to get a file object for Pillow. We might have a path or we might # have to read the data into memory. if hasattr(data, "temporary_file_path"): with open(data.temporary_file_path(), "rb") as temp_fp: file = BytesIO(temp_fp.read()) else: if hasattr(data, "read"): file = BytesIO(data.read()) else: file = BytesIO(data["content"]) try: # load() could spot a truncated JPEG, but it loads the entire # image in memory, which is a DoS vector. See #3848 and #18520. image = Image.open(file) # verify() must be called immediately after the constructor. image.verify() # Annotating so subclasses can reuse it for their own validation f.image = image # Pillow doesn't detect the MIME type of all formats. In those # cases, content_type will be None. f.content_type = Image.MIME.get(image.format) except Exception as exc: # Pillow doesn't recognize it as an image. raise ValidationError( _("Upload a valid image. The file you uploaded was either not an " "image or a corrupted image.")) from exc if hasattr(f, "seek") and callable(f.seek): f.seek(0) stream = BytesIO() extension = ".jpg" if image.mode == "RGBA": extension = ".png" elif image.mode != "RGB": image = image.convert("RGB") stream.name = Path(data.name).stem + extension image.fp = file if hasattr(image, "png"): # Yeah, idk what's up with this image.png.fp = file image_data = image.getdata() image_without_exif = Image.new(image.mode, image.size) image_without_exif.putdata(image_data) if self.max_height and self.max_width: image_without_exif.thumbnail((self.max_width, self.max_height)) image_without_exif.save( stream, quality="web_high" if extension == ".jpg" else 95) stream.seek(0) return File(stream, name=data.name)
def clean_date_from(self): period = self.cleaned_data['period'] date_from = self.cleaned_data['date_from'] if period == 'other' and date_from is None: raise ValidationError(_('Must specify start of period')) return date_from
def get_queryset(self): # noqa C901 form = SolicitacoesAtivasInativasPorAlunoForm(self.request.GET) if not form.is_valid(): raise ValidationError(form.errors) user = self.request.user instituicao = user.vinculo_atual.instituicao if user.tipo_usuario == 'escola': dietas_autorizadas = SolicitacoesEscola.get_autorizados_dieta_especial( escola_uuid=instituicao.uuid) dietas_inativas = SolicitacoesEscola.get_inativas_dieta_especial( escola_uuid=instituicao.uuid) elif user.tipo_usuario == 'diretoriaregional': dietas_autorizadas = SolicitacoesDRE.get_autorizados_dieta_especial( dre_uuid=instituicao.uuid) dietas_inativas = SolicitacoesDRE.get_inativas_dieta_especial( dre_uuid=instituicao.uuid) else: dietas_autorizadas = SolicitacoesCODAE.get_autorizados_dieta_especial( ) dietas_inativas = SolicitacoesCODAE.get_inativas_dieta_especial() # Retorna somente Dietas Autorizadas ids_dietas_autorizadas = dietas_autorizadas.values_list('id', flat=True) # Retorna somente Dietas Inativas. ids_dietas_inativas = dietas_inativas.values_list('id', flat=True) INATIVOS_STATUS_DIETA_ESPECIAL = [ 'CODAE_AUTORIZADO', 'CODAE_AUTORIZOU_INATIVACAO', 'TERMINADA_AUTOMATICAMENTE_SISTEMA' ] # Retorna somente Dietas Autorizadas e Inativas. qs = Aluno.objects.filter( dietas_especiais__status__in=INATIVOS_STATUS_DIETA_ESPECIAL ).annotate( ativas=Count( 'dietas_especiais', filter=Q(dietas_especiais__id__in=ids_dietas_autorizadas)), inativas=Count( 'dietas_especiais', filter=Q(dietas_especiais__id__in=ids_dietas_inativas)), ).filter(Q(ativas__gt=0) | Q(inativas__gt=0)) if user.tipo_usuario == 'escola': qs = qs.filter(escola=user.vinculo_atual.instituicao) elif form.cleaned_data['escola']: qs = qs.filter(escola=form.cleaned_data['escola']) elif user.tipo_usuario == 'diretoriaregional': qs = qs.filter( escola__diretoria_regional=user.vinculo_atual.instituicao) elif form.cleaned_data['dre']: qs = qs.filter(escola__diretoria_regional=form.cleaned_data['dre']) if form.cleaned_data['codigo_eol']: codigo_eol = f"{int(form.cleaned_data['codigo_eol']):06d}" qs = qs.filter(codigo_eol=codigo_eol) elif form.cleaned_data['nome_aluno']: qs = qs.filter(nome__icontains=form.cleaned_data['nome_aluno']) if self.request.user.tipo_usuario == 'dieta_especial': return qs.order_by('escola__diretoria_regional__nome', 'escola__nome', 'nome') elif self.request.user.tipo_usuario == 'diretoriaregional': return qs.order_by('escola__nome', 'nome') return qs.order_by('nome')
def validate(self, value): if not value: raise ValidationError('no value', code='required')
def clean_username(self, username): if len(username) > 10: raise ValidationError( 'Please enter a username value less than the current one') return DefaultAccountAdapter.clean_username( self, username) # For other default validations
def user_filter_exception(user): if user.get_username() == 'bar': raise ValidationError(['first good reason', "anyway, I don't like {0}".format(user.get_username())]) return None
def clean_confirm(self): if not self.cleaned_data['confirm']: raise ValidationError( "Please check this box to confirm that you are really sending this email! There is no going back!" )
def exch_filter_exception(sender, recipient, recipients_list): if recipient.get_username() == 'bar': raise ValidationError(['first good reason', "anyway, I don't like {0}".format(recipient.get_username())]) return None
def clean_type(self): if self.cleaned_data['type'] != 'review': raise ValidationError('Invalid value') return self.cleaned_data['type']
def lnglat_validator(value): if not re.match(r'^([+-]?\d+\.?\d*),([+-]?\d+\.?\d*)$', value): raise ValidationError('Invalid LngLat Type')
def clean(self): if any(self.errors): #return raise ValidationError('Please add at least one vehicle.')
def clean_age(self): data = self.cleaned_data['age'] if data < 18: raise ValidationError("Your are too young") return data
def clean_student_group(self): groups = Group.objects.filter(leader=self.instance) if len(groups) > 0 and self.cleaned_data['student_group'] != groups[0]: raise ValidationError("Student is leader one of other groups.", code='invalid') return self.cleaned_data['student_group']
def clean_ablaufdatum(self): ablaufdatum = self.cleaned_data.get('ablaufdatum') if ablaufdatum < date.today(): raise ValidationError( "Das Ablaufdatum kann nicht in der Vergangenheit liegen.") return ablaufdatum
def clean_course(self): try: course = Course.objects.get(abreviation=self.data['course']) except Course.DoesNotExist: raise ValidationError(f"El curso con la abreviación {self.data['course']} no existe 💥") return course
def clean_email(self): email = self.cleaned_data['email'] if not User.objects.filter(email__iexact=email, is_active=True).exists(): raise ValidationError(_("There is no user registered with the specified email address!")) return email
def handle(self, request, data): try: usages = quotas.tenant_limit_usages(self.request) availableGB = usages['maxTotalVolumeGigabytes'] - \ usages['gigabytesUsed'] availableVol = usages['maxTotalVolumes'] - usages['volumesUsed'] snapshot_id = None image_id = None volume_id = None source_type = data.get('volume_source_type', None) az = data.get('availability_zone', None) or None if (data.get("snapshot_source", None) and source_type in ['', None, 'snapshot_source']): # Create from Snapshot snapshot = self.get_snapshot(request, data["snapshot_source"]) snapshot_id = snapshot.id if (data['size'] < snapshot.size): error_message = (_('The volume size cannot be less than ' 'the snapshot size (%sGB)') % snapshot.size) raise ValidationError(error_message) az = None elif (data.get("image_source", None) and source_type in ['', None, 'image_source']): # Create from Snapshot image = self.get_image(request, data["image_source"]) image_id = image.id image_size = functions.bytes_to_gigabytes(image.size) if (data['size'] < image_size): error_message = (_('The volume size cannot be less than ' 'the image size (%s)') % filesizeformat(image.size)) raise ValidationError(error_message) properties = getattr(image, 'properties', {}) min_disk_size = (getattr(image, 'min_disk', 0) or properties.get('min_disk', 0)) if (min_disk_size > 0 and data['size'] < min_disk_size): error_message = (_('The volume size cannot be less than ' 'the image minimum disk size (%sGB)') % min_disk_size) raise ValidationError(error_message) elif (data.get("volume_source", None) and source_type in ['', None, 'volume_source']): # Create from volume volume = self.get_volume(request, data["volume_source"]) volume_id = volume.id if data['size'] < volume.size: error_message = (_('The volume size cannot be less than ' 'the source volume size (%sGB)') % volume.size) raise ValidationError(error_message) else: if type(data['size']) is str: data['size'] = int(data['size']) if availableGB < data['size']: error_message = _('A volume of %(req)iGB cannot be created as ' 'you only have %(avail)iGB of your quota ' 'available.') params = {'req': data['size'], 'avail': availableGB} raise ValidationError(error_message % params) elif availableVol <= 0: error_message = _('You are already using all of your available' ' volumes.') raise ValidationError(error_message) metadata = {} volume = cinder.volume_create(request, data['size'], data['name'], data['description'], data['type'], snapshot_id=snapshot_id, image_id=image_id, metadata=metadata, availability_zone=az, source_volid=volume_id) message = _('Creating volume "%s"') % data['name'] messages.info(request, message) return volume except ValidationError as e: self.api_error(e.messages[0]) return False except Exception: redirect = reverse("horizon:project:volumes:index") exceptions.handle(request, _("Unable to create volume."), redirect=redirect)
def from_pgraster(data): """ Convert a PostGIS HEX String into a dictionary. """ if data is None: return # Split raster header from data header, data = chunk(data, 122) header = unpack(POSTGIS_HEADER_STRUCTURE, header) # Parse band data bands = [] pixeltypes = [] while data: # Get pixel type for this band pixeltype, data = chunk(data, 2) pixeltype = unpack('B', pixeltype)[0] # Subtract nodata byte from band nodata value if it exists has_nodata = pixeltype >= 64 if has_nodata: pixeltype -= 64 # Convert datatype from PostGIS to GDAL & get pack type and size pixeltype = POSTGIS_TO_GDAL[pixeltype] pack_type = GDAL_TO_STRUCT[pixeltype] pack_size = 2 * STRUCT_SIZE[pack_type] # Parse band nodata value. The nodata value is part of the # PGRaster string even if the nodata flag is True, so it always # has to be chunked off the data string. nodata, data = chunk(data, pack_size) nodata = unpack(pack_type, nodata)[0] # Chunk and unpack band data (pack size times nr of pixels) band, data = chunk(data, pack_size * header[10] * header[11]) band_result = {'data': binascii.unhexlify(band)} # If the nodata flag is True, set the nodata value. if has_nodata: band_result['nodata_value'] = nodata # Append band data to band list bands.append(band_result) # Store pixeltype of this band in pixeltypes array pixeltypes.append(pixeltype) # Check that all bands have the same pixeltype. # This is required by GDAL. PostGIS rasters could have different pixeltypes # for bands of the same raster. if len(set(pixeltypes)) != 1: raise ValidationError("Band pixeltypes are not all equal.") return { 'srid': int(header[9]), 'width': header[10], 'height': header[11], 'datatype': pixeltypes[0], 'origin': (header[5], header[6]), 'scale': (header[3], header[4]), 'skew': (header[7], header[8]), 'bands': bands, }
def clean_username(self): user = self.cleaned_data.get("username") ret = models.UserInfo.objects.filter(username=user).first() if ret: raise ValidationError("用户名已经存在!")
def _pages_from_json(request, offering, data): with django.db.transaction.atomic(): try: data = data.decode('utf-8') except UnicodeDecodeError: raise ValidationError(u"Bad UTF-8 data in file.") try: data = json.loads(data) except ValueError as e: raise ValidationError(u'JSON decoding error. Exception was: "' + str(e) + '"') if not isinstance(data, dict): raise ValidationError(u'Outer JSON data structure must be an object.') if 'userid' not in data or 'token' not in data: raise ValidationError(u'Outer JSON data object must contain keys "userid" and "token".') if 'pages' not in data: raise ValidationError(u'Outer JSON data object must contain keys "pages".') if not isinstance(data['pages'], list): raise ValidationError(u'Value for "pages" must be a list.') try: user = Person.objects.get(userid=data['userid']) member = Member.objects.exclude(role='DROP').get(person=user, offering=offering) except Person.DoesNotExist, Member.DoesNotExist: raise ValidationError(u'Person with that userid does not exist.') if 'pages-token' not in user.config or user.config['pages-token'] != data['token']: e = ValidationError(u'Could not validate authentication token.') e.status = 403 raise e # if we get this far, the user is authenticated and we can start processing the pages... for i, pdata in enumerate(data['pages']): if not isinstance(pdata, dict): raise ValidationError(u'Page #%i entry structure must be an object.' % (i)) if 'label' not in pdata: raise ValidationError(u'Page #%i entry does not have a "label".' % (i)) # handle changes to the Page object pages = Page.objects.filter(offering=offering, label=pdata['label']) if pages: page = pages[0] old_ver = page.current_version() else: page = Page(offering=offering, label=pdata['label']) old_ver = None # check write permissions # mock the request object enough to satisfy _check_allowed() class FakeRequest(object): pass fake_request = FakeRequest() fake_request.user = FakeRequest() fake_request.user.username = user.userid if old_ver: m = _check_allowed(fake_request, offering, page.can_write, page.editdate()) else: m = _check_allowed(fake_request, offering, offering.page_creators()) if not m: raise ValidationError(u'You can\'t edit page #%i.' % (i)) # handle Page attributes if 'can_read' in pdata: if type(pdata['can_read']) != unicode or pdata['can_read'] not in ACL_DESC: raise ValidationError(u'Page #%i "can_read" value must be one of %s.' % (i, ','.join(ACL_DESC.keys()))) page.can_read = pdata['can_read'] if 'can_write' in pdata: if type(pdata['can_write']) != unicode or pdata['can_write'] not in WRITE_ACL_DESC: raise ValidationError(u'Page #%i "can_write" value must be one of %s.' % (i, ','.join(WRITE_ACL_DESC.keys()))) if m.role == 'STUD': raise ValidationError(u'Page #%i: students can\'t change can_write value.' % (i)) page.can_write = pdata['can_write'] if 'new_label' in pdata: if type(pdata['new_label']) != unicode: raise ValidationError(u'Page #%i "new_label" value must be a string.' % (i)) if m.role == 'STUD': raise ValidationError(u'Page #%i: students can\'t change label value.' % (i)) if Page.objects.filter(offering=offering, label=pdata['new_label']): raise ValidationError(u'Page #%i: there is already a page with that "new_label".' % (i)) page.label = pdata['new_label'] page.save() # handle PageVersion changes ver = PageVersion(page=page, editor=member) if 'title' in pdata: if type(pdata['title']) != unicode: raise ValidationError(u'Page #%i "title" value must be a string.' % (i)) ver.title = pdata['title'] elif old_ver: ver.title = old_ver.title else: raise ValidationError(u'Page #%i has no "title" for new page.' % (i)) if 'comment' in pdata: if type(pdata['comment']) != unicode: raise ValidationError(u'Page #%i "comment" value must be a string.' % (i)) ver.comment = pdata['comment'] if 'use_math' in pdata: if type(pdata['use_math']) != bool: raise ValidationError(u'Page #%i "comment" value must be a boolean.' % (i)) ver.set_math(pdata['use_math']) if 'wikitext-base64' in pdata: if type(pdata['wikitext-base64']) != unicode: raise ValidationError(u'Page #%i "wikitext-base64" value must be a string.' % (i)) try: wikitext = base64.b64decode(pdata['wikitext-base64']) except TypeError: raise ValidationError(u'Page #%i "wikitext-base64" contains bad base BASE64 data.' % (i)) ver.wikitext = wikitext elif 'wikitext' in pdata: if type(pdata['wikitext']) != unicode: raise ValidationError(u'Page #%i "wikitext" value must be a string.' % (i)) ver.wikitext = pdata['wikitext'] elif old_ver: ver.wikitext = old_ver.wikitext else: raise ValidationError(u'Page #%i has no wikitext for new page.' % (i)) ver.save() return user