Python horizon.forms.ValidationError() Examples

The following are 30 code examples of horizon.forms.ValidationError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module horizon.forms , or try the search function .
Example #1
Source File: forms.py    From cloudkitty-dashboard with Apache License 2.0 6 votes vote down vote up
def clean_uploaded_files(self, prefix, files):
        upload_str = prefix + "_upload"

        has_upload = upload_str in files
        if has_upload:
            upload_file = files[upload_str]
            log_script_name = upload_file.name
            LOG.info('got upload %s' % log_script_name)
            script = upload_file.read()
            if script != "":
                try:
                    normalize_newlines(script)
                except Exception as e:
                    msg = _('There was a problem parsing the'
                            ' %(prefix)s: %(error)s')
                    msg = msg % {'prefix': prefix, 'error': e}
                    raise forms.ValidationError(msg)
            return script
        else:
            return None 
Example #2
Source File: workflows.py    From avos with Apache License 2.0 6 votes vote down vote up
def clean(self):
        cleaned_data = super(UpdateProjectQuotaAction, self).clean()
        usages = quotas.tenant_quota_usages(
            self.request, tenant_id=self.initial['project_id'])
        # Validate the quota values before updating quotas.
        bad_values = []
        for key, value in cleaned_data.items():
            used = usages[key].get('used', 0)
            if value is not None and value >= 0 and used > value:
                bad_values.append(_('%(used)s %(key)s used') %
                                  {'used': used,
                                   'key': quotas.QUOTA_NAMES.get(key, key)})
        if bad_values:
            value_str = ", ".join(bad_values)
            msg = (_('Quota value(s) cannot be less than the current usage '
                     'value(s): %s.') %
                   value_str)
            raise forms.ValidationError(msg)
        return cleaned_data 
Example #3
Source File: workflows.py    From avos with Apache License 2.0 6 votes vote down vote up
def clean(self):
        cleaned_data = super(CreateFlavorInfoAction, self).clean()
        name = cleaned_data.get('name')
        flavor_id = cleaned_data.get('flavor_id')

        try:
            flavors = api.nova.flavor_list(self.request, None)
        except Exception:
            flavors = []
            msg = _('Unable to get flavor list')
            exceptions.check_message(["Connection", "refused"], msg)
            raise
        if flavors is not None:
            for flavor in flavors:
                if flavor.name == name:
                    raise forms.ValidationError(
                        _('The name "%s" is already used by another flavor.')
                        % name
                    )
                if flavor.id == flavor_id:
                    raise forms.ValidationError(
                        _('The ID "%s" is already used by another flavor.')
                        % flavor_id
                    )
        return cleaned_data 
Example #4
Source File: forms.py    From avos with Apache License 2.0 6 votes vote down vote up
def clean_qos_spec_choice(self):
        # ensure that new association isn't the same as current association
        cleaned_new_spec_id = self.cleaned_data.get('qos_spec_choice')
        cur_spec_id = self.initial['cur_qos_spec_id']

        found_error = False
        if cur_spec_id:
            # new = current
            if cur_spec_id == cleaned_new_spec_id:
                found_error = True
        else:
            # no current association
            if cleaned_new_spec_id == '-1':
                # new = current
                found_error = True

        if found_error:
            raise forms.ValidationError(
                _('New associated QoS Spec must be different than '
                  'the current associated QoS Spec.'))
        return cleaned_new_spec_id 
Example #5
Source File: forms.py    From django-leonardo with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def clean(self):
        '''Check to make sure password fields match.'''
        data = super(SignupForm, self).clean()

        # basic check for now
        if 'username' in data:
            if User.objects.filter(
                    username=data['username'],
                    email=data['email']).exists():
                raise validators.ValidationError(
                    _('Username or email exists in database.'))

        if 'password' in data:
            if data['password'] != data.get('confirm_password', None):
                raise validators.ValidationError(_('Passwords do not match.'))
            else:
                data.pop('confirm_password')
        return data 
Example #6
Source File: workflows.py    From avos with Apache License 2.0 6 votes vote down vote up
def clean(self):
        cleaned_data = super(SetAggregateInfoAction, self).clean()
        name = cleaned_data.get('name')

        try:
            aggregates = api.nova.aggregate_details_list(self.request)
        except Exception:
            msg = _('Unable to get host aggregate list')
            exceptions.check_message(["Connection", "refused"], msg)
            raise
        if aggregates is not None:
            for aggregate in aggregates:
                if aggregate.name.lower() == name.lower():
                    raise forms.ValidationError(
                        _('The name "%s" is already used by '
                          'another host aggregate.')
                        % name
                    )
        return cleaned_data 
Example #7
Source File: create_instance.py    From avos with Apache License 2.0 6 votes vote down vote up
def clean_uploaded_files(self, prefix, files):
        upload_str = prefix + "_upload"

        has_upload = upload_str in files
        if has_upload:
            upload_file = files[upload_str]
            log_script_name = upload_file.name
            LOG.info('got upload %s' % log_script_name)

            if upload_file._size > 16 * 1024:  # 16kb
                msg = _('File exceeds maximum size (16kb)')
                raise forms.ValidationError(msg)
            else:
                script = upload_file.read()
                if script != "":
                    try:
                        normalize_newlines(script)
                    except Exception as e:
                        msg = _('There was a problem parsing the'
                                ' %(prefix)s: %(error)s')
                        msg = msg % {'prefix': prefix, 'error': e}
                        raise forms.ValidationError(msg)
                return script
        else:
            return None 
Example #8
Source File: workflows.py    From avos with Apache License 2.0 6 votes vote down vote up
def _check_allocation_pools(self, allocation_pools):
        for p in allocation_pools.split('\n'):
            p = p.strip()
            if not p:
                continue
            pool = p.split(',')
            if len(pool) != 2:
                msg = _('Start and end addresses must be specified '
                        '(value=%s)') % p
                raise forms.ValidationError(msg)
            start, end = [self._convert_ip_address(ip, "allocation_pools")
                          for ip in pool]
            if start > end:
                msg = _('Start address is larger than end address '
                        '(value=%s)') % p
                raise forms.ValidationError(msg) 
Example #9
Source File: forms.py    From mistral-dashboard with Apache License 2.0 6 votes vote down vote up
def clean(self):
        cleaned_data = super(DefinitionForm, self).clean()

        if cleaned_data.get('definition_upload'):
            files = self.request.FILES
            cleaned_data['definition'] = files['definition_upload'].read()
        elif cleaned_data.get('definition_data'):
            cleaned_data['definition'] = cleaned_data['definition_data']
        else:
            raise forms.ValidationError(
                _('You must specify the definition source.'))
        try:
            validated = api.workbook_validate(
                self.request,
                cleaned_data['definition']
            )
        except Exception as e:
            raise forms.ValidationError(str(e))

        if not validated.get('valid'):
            raise forms.ValidationError(
                validated.get('error', _('Validated failed')))

        return cleaned_data 
Example #10
Source File: forms.py    From mistral-dashboard with Apache License 2.0 6 votes vote down vote up
def clean(self):
        cleaned_data = super(DefinitionForm, self).clean()

        if cleaned_data.get('definition_upload'):
            files = self.request.FILES
            cleaned_data['definition'] = files['definition_upload'].read()
        elif cleaned_data.get('definition_data'):
            cleaned_data['definition'] = cleaned_data['definition_data']
        else:
            raise forms.ValidationError(
                _('You must specify the definition source.'))
        try:
            validated = api.workflow_validate(
                self.request,
                cleaned_data['definition']
            )
        except Exception as e:
            raise forms.ValidationError(str(e))

        if not validated.get('valid'):
            raise forms.ValidationError(
                validated.get('error', _('Validated failed')))

        return cleaned_data 
Example #11
Source File: workflows.py    From avos with Apache License 2.0 5 votes vote down vote up
def _convert_ip_address(self, ip, field_name):
        try:
            return netaddr.IPAddress(ip)
        except (netaddr.AddrFormatError, ValueError):
            msg = (_('%(field_name)s: Invalid IP address (value=%(ip)s)')
                   % {'field_name': field_name, 'ip': ip})
            raise forms.ValidationError(msg) 
Example #12
Source File: forms.py    From avos with Apache License 2.0 5 votes vote down vote up
def clean(self):
        cleaned_data = super(ResizeInstanceForm, self).clean()
        flavor = cleaned_data.get('new_flavor', None)

        if flavor is None or flavor == self.initial['old_flavor_id']:
            raise forms.ValidationError(_('Please choose a new flavor that '
                                          'is not the same as the old one.'))
        return cleaned_data 
Example #13
Source File: workflows.py    From avos with Apache License 2.0 5 votes vote down vote up
def _convert_ip_network(self, network, field_name):
        try:
            return netaddr.IPNetwork(network)
        except (netaddr.AddrFormatError, ValueError):
            msg = (_('%(field_name)s: Invalid IP address (value=%(network)s)')
                   % {'field_name': field_name, 'network': network})
            raise forms.ValidationError(msg) 
Example #14
Source File: workflows.py    From avos with Apache License 2.0 5 votes vote down vote up
def _check_host_routes(self, host_routes):
        for r in host_routes.split('\n'):
            r = r.strip()
            if not r:
                continue
            route = r.split(',')
            if len(route) != 2:
                msg = _('Host Routes format error: '
                        'Destination CIDR and nexthop must be specified '
                        '(value=%s)') % r
                raise forms.ValidationError(msg)
            self._convert_ip_network(route[0], "host_routes")
            self._convert_ip_address(route[1], "host_routes") 
Example #15
Source File: tests.py    From avos with Apache License 2.0 5 votes vote down vote up
def test_clean_file_upload_form_oversize_data(self):
        t = workflows.create_instance.CustomizeAction(self.request, {})
        upload_str = 'user data'
        files = {'script_upload':
                 self.SimpleFile('script_name',
                                 upload_str,
                                 (16 * 1024) + 1)}

        self.assertRaises(
            forms.ValidationError,
            t.clean_uploaded_files,
            'script',
            files) 
Example #16
Source File: resize_instance.py    From avos with Apache License 2.0 5 votes vote down vote up
def clean(self):
        cleaned_data = super(SetFlavorChoiceAction, self).clean()
        flavor = cleaned_data.get('flavor', None)

        if flavor is None or flavor == cleaned_data['old_flavor_id']:
            raise forms.ValidationError(_('Please choose a new flavor that '
                                          'is not the same as the old one.'))
        return cleaned_data 
Example #17
Source File: create_instance.py    From avos with Apache License 2.0 5 votes vote down vote up
def _check_source_volume(self, cleaned_data):
        if not cleaned_data.get('volume_id'):
            msg = _("You must select a volume.")
            self._errors['volume_id'] = self.error_class([msg])
        # Prevent launching multiple instances with the same volume.
        # TODO(gabriel): is it safe to launch multiple instances with
        # a snapshot since it should be cloned to new volumes?
        count = cleaned_data.get('count', 1)
        if count > 1:
            msg = _('Launching multiple instances is only supported for '
                    'images and instance snapshots.')
            raise forms.ValidationError(msg) 
Example #18
Source File: create_instance.py    From avos with Apache License 2.0 5 votes vote down vote up
def clean(self):
        '''Check to make sure password fields match.'''
        cleaned_data = super(SetAccessControlsAction, self).clean()
        if 'admin_pass' in cleaned_data:
            if cleaned_data['admin_pass'] != cleaned_data.get(
                    'confirm_admin_pass', None):
                raise forms.ValidationError(_('Passwords do not match.'))
        return cleaned_data 
Example #19
Source File: forms.py    From avos with Apache License 2.0 5 votes vote down vote up
def clean(self):
        data = super(CreateNamespaceForm, self).clean()

        # The key can be missing based on particular upload
        # conditions. Code defensively for it here...
        metadef_file = data.get('metadef_file', None)
        metadata_raw = data.get('direct_input', None)

        if metadata_raw and metadef_file:
            raise ValidationError(
                _("Cannot specify both file and direct input."))
        if not metadata_raw and not metadef_file:
            raise ValidationError(
                _("No input was provided for the namespace content."))
        try:
            if metadef_file:
                ns_str = self.files['metadef_file'].read()
            else:
                ns_str = data['direct_input']
            namespace = json.loads(ns_str)

            if data['public']:
                namespace['visibility'] = 'public'
            else:
                namespace['visibility'] = 'private'

            namespace['protected'] = data['protected']

            for protected_prop in constants.METADEFS_PROTECTED_PROPS:
                namespace.pop(protected_prop, None)

            data['namespace'] = namespace
        except Exception as e:
            msg = _('There was a problem loading the namespace: %s.') % e
            raise forms.ValidationError(msg)

        return data 
Example #20
Source File: forms.py    From avos with Apache License 2.0 5 votes vote down vote up
def clean_consumer_choice(self):
        # ensure that new consumer isn't the same as current consumer
        qos_spec = self.initial['qos_spec']
        cleaned_new_consumer = self.cleaned_data.get('consumer_choice')
        old_consumer = qos_spec.consumer

        if cleaned_new_consumer == old_consumer:
            raise forms.ValidationError(
                _('QoS Spec consumer value must be different than '
                  'the current consumer value.'))
        return cleaned_new_consumer 
Example #21
Source File: forms.py    From django-leonardo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def clean_password2(self):
        if ("password1" in self.cleaned_data
                and "password2" in self.cleaned_data):
            if (self.cleaned_data["password1"]
                    != self.cleaned_data["password2"]):
                raise forms.ValidationError(_("You must type the same"
                                              " password each time."))
        return self.cleaned_data["password2"] 
Example #22
Source File: forms.py    From monasca-ui with Apache License 2.0 5 votes vote down vote up
def clean_period(self):
        '''Check to make sure period is zero unless type is WEBHOOK.

        For WEBHOOK period must be set to 0 or 60.
        '''
        data = self.cleaned_data
        if data['type'] != constants.NotificationType.WEBHOOK and data['period'] != '0':
            raise forms.ValidationError(
                _('Period must be zero except for type webhook.'))

        return data['period'] 
Example #23
Source File: forms.py    From monasca-ui with Apache License 2.0 5 votes vote down vote up
def clean_expression(self):
        data = self.cleaned_data['expression']
        value = data.split(' ')[2]
        if not value.isdigit():
            raise forms.ValidationError("Value must be an integer")

        # Always return the cleaned data, whether you have changed it or
        # not.
        return data 
Example #24
Source File: forms.py    From tacker-horizon with Apache License 2.0 5 votes vote down vote up
def clean(self):
        data = super(OnBoardVNF, self).clean()

        # The key can be missing based on particular upload
        # conditions. Code defensively for it here...
        toscal_file = data.get('toscal_file', None)
        toscal_raw = data.get('direct_input', None)
        source_type = data.get("source_type")
        if source_type == "file" and not toscal_file:
            raise ValidationError(
                _("No TOSCA template file selected."))
        if source_type == "raw" and not toscal_raw:
            raise ValidationError(
                _("No direct input specified."))

        if toscal_file and not toscal_file.name.endswith(('.yaml', '.csar')):
            raise ValidationError(_("Only .yaml or .csar file uploads \
                                    are supported"))

        try:
            if toscal_file:
                toscal_str = self.files['toscal_file'].read()
            else:
                toscal_str = data['direct_input']
            # toscal = yaml.loads(toscal_str)
            data['tosca'] = toscal_str
        except Exception as e:
            msg = _('There was a problem loading the namespace: %s.') % e
            raise forms.ValidationError(msg)

        return data 
Example #25
Source File: forms.py    From tacker-horizon with Apache License 2.0 5 votes vote down vote up
def clean(self):
        data = super(OnBoardVNFFG, self).clean()

        # The key can be missing based on particular upload
        # conditions. Code defensively for it here...
        toscal_file = data.get('toscal_file', None)
        toscal_raw = data.get('direct_input', None)

        if toscal_raw and toscal_file:
            raise ValidationError(
                _("Cannot specify both file and direct input."))
        if not toscal_raw and not toscal_file:
            raise ValidationError(
                _("No input was provided for the namespace content."))

        if toscal_file and not toscal_file.name.endswith(('.yaml', '.csar')):
            raise ValidationError(_("Only .yaml or .csar file uploads \
                                    are supported"))

        try:
            if toscal_file:
                toscal_str = self.files['toscal_file'].read()
            else:
                toscal_str = data['direct_input']
            toscal = yaml.safe_load(toscal_str)
            data['tosca'] = toscal
        except Exception as e:
            msg = _('There was a problem loading the namespace: %s.') % e
            raise forms.ValidationError(msg)

        return data 
Example #26
Source File: forms.py    From tacker-horizon with Apache License 2.0 5 votes vote down vote up
def clean(self):
        data = super(OnBoardNS, self).clean()

        # The key can be missing based on particular upload
        # conditions. Code defensively for it here...
        toscal_file = data.get('toscal_file', None)
        toscal_raw = data.get('direct_input', None)
        source_type = data.get("source_type")
        if source_type == "file" and not toscal_file:
            raise ValidationError(
                _("No TOSCA template file selected."))
        if source_type == "raw" and not toscal_raw:
            raise ValidationError(
                _("No direct input specified."))

        if toscal_file and not toscal_file.name.endswith(('.yaml', '.csar')):
            raise ValidationError(_("Only .yaml or .csar file uploads \
                                    are supported"))

        try:
            if toscal_file:
                toscal_str = self.files['toscal_file'].read()
            else:
                toscal_str = data['direct_input']
            # toscal = yaml.loads(toscal_str)
            data['tosca'] = toscal_str
        except Exception as e:
            msg = _('There was a problem loading the namespace: %s.') % e
            raise forms.ValidationError(msg)

        return data 
Example #27
Source File: forms.py    From django-leonardo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def clean_oldpassword(self):
        if not self.user.check_password(self.cleaned_data.get("oldpassword")):
            raise forms.ValidationError(_("Please type your current"
                                          " password."))
        return self.cleaned_data["oldpassword"] 
Example #28
Source File: forms.py    From django-leonardo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def clean_password2(self):
        if ("password1" in self.cleaned_data
                and "password2" in self.cleaned_data):

            if (self.cleaned_data["password1"]
                    != self.cleaned_data["password2"]):
                raise forms.ValidationError(_("You must type the same password"
                                              " each time."))
        return self.cleaned_data["password2"] 
Example #29
Source File: forms.py    From django-leonardo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def clean_email(self):
        email = self.cleaned_data["email"]

        self.users = get_user_model().objects \
            .filter(Q(email__iexact=email)).distinct()

        if not self.users.exists():
            raise forms.ValidationError(_("The e-mail address is not assigned"
                                          " to any user account"))
        return self.cleaned_data["email"] 
Example #30
Source File: forms.py    From avos with Apache License 2.0 5 votes vote down vote up
def clean(self):
        cleaned = super(TemplateForm, self).clean()

        files = self.request.FILES
        self.clean_uploaded_files('template', _('template'), cleaned, files)
        self.clean_uploaded_files('environment',
                                  _('environment'),
                                  cleaned,
                                  files)

        # Validate the template and get back the params.
        kwargs = {}
        if cleaned['template_data']:
            kwargs['template'] = cleaned['template_data']
        else:
            kwargs['template_url'] = cleaned['template_url']

        if cleaned['environment_data']:
            kwargs['environment'] = cleaned['environment_data']

        try:
            validated = api.heat.template_validate(self.request, **kwargs)
            cleaned['template_validate'] = validated
        except Exception as e:
            raise forms.ValidationError(unicode(e))

        return cleaned